Two Little Problems

Two little problems that you may encounter in a Windows Application project:

1- You are using a DataGridView and want to change some (all) rows’ (cells) style, for example their color. Setting the Style property of rows or cells is the way to do so, but it won’t change anything unless done in dataGridView_RowsAdded event handler - at least I couldn’t find any other way to make it work.

2- You have a TabControl and usually want to make TabPages closable (using a ContextMenu)
and ,of course, don’t want the context menu to open inside the client area of the tab page, but just on the small header rectangle, as in VisualStudio tab pages.

Solution: ContextMenu has an Opening event and TabControl has a MouseDown event which fires before the ‘Opening’ event, so you’re gonna use them to cancel the opening whenever the click is not in the right place. Obviously, you should use a private bool allowContextMenuOpening.

private void tabControlPrograms_MouseDown(object sender, MouseEventArgs e)
{
   if (e.Button == MouseButtons.Right)
      for (int i = 0; i < tabControlPrograms.TabCount; i++)
         if (tabControlPrograms.GetTabRect(i).Contains(e.Location))
         {
            allowContextMenuOpening = true;
            return;
         }
}

private void closeVisitorContextMenu_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
   if (!allowContextMenuOpening)
      e.Cancel = true;
   else
      allowContextMenuOpening = false;
}

Mahdieh

Tags: , ,

Leave a Reply