Determine the type of a row in a DataGridView using a DataTable data source

354 Views Asked by At

I have been writing a small winforms program using the DataGridView control, using List<> as the data source. I used the following MouseClick event to show a specific context menu depending on the data being shown in the grid (there are three options at the moment).

private void DataGridView_MouseClick(object sender, MouseEventArgs e)
{
   if (e.Button == MouseButtons.Right)
   {
      int currentMouseOverRow = dataGridView.HitTest(e.X, e.Y).RowIndex;

      // Clicking on a row?
      if (currentMouseOverRow >= 0 && currentMouseOverRow <= dataGridView.Rows.Count - 1)
      {
         ContextMenuStrip m;

         if (dataGridView.SelectedRows[0].DataBoundItem.GetType() == typeof(DataGrid))
            m = gridViewContextDataMenuStrip;
         else if (dataGridView.SelectedRows[0].DataBoundItem.GetType() == typeof(InfoGrid))
            m = gridViewContextInfoMenuStrip;
         else
            return;

         m.Show(dataGridView, new Point(e.X, e.Y));
      }
   }
}

This worked as expected and all was good. But then I wanted to added column sorting, so I changed the data source from List<> to DataTable.

Now the MouseClick event no longer works because the DataBoundItem.GetType() now no longer returns the expected type. I have been looking for how to modify the code to get the correct type from the DataTable row in order for the method to start working again, but with no luck so far. Can anyone point me in the right direction.

Many thanks.

1

There are 1 best solutions below

0
Stephen Cooper On

After replying to the question from Caius, I went back to the code I had taken to convert IEnumerables to a DataTable. It clicked that of course there would be no link back to the original data type since the columns and rows were being copied by reflection into an completely new DataTable.

As a quick fix (that will probably last) I have added a second parameter to pass in a string containing the 'data type' and setting that as the DataTable.TableName. Using this I can check in the MouseDown method to tell the different DataTables apart.

Thanks for reading.