0

我一直在使用 DataGridView 控件编写一个小型 winforms 程序,使用 List<> 作为数据源。我使用以下 MouseClick 事件来显示特定的上下文菜单,具体取决于网格中显示的数据(目前有三个选项)。

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));
      }
   }
}

这按预期工作,一切都很好。但是后来我想添加列排序,所以我将数据源从 List<> 更改为 DataTable。

现在 MouseClick 事件不再起作用,因为 DataBoundItem.GetType() 现在不再返回预期的类型。我一直在寻找如何修改代码以从 DataTable 行中获取正确的类型,以便该方法再次开始工作,但到目前为止还没有运气。谁能指出我正确的方向。

非常感谢。

4

1 回答 1

0

在回答了 Caius 的问题后,我回到了将 IEnumerables 转换为 DataTable 的代码。它点击了,当然不会有返回原始数据类型的链接,因为列和行正在通过反射复制到一个全新的 DataTable 中。

作为快速修复(可能会持续),我添加了第二个参数来传递包含“数据类型”的字符串并将其设置为 DataTable.TableName。使用它我可以检查 MouseDown 方法来区分不同的 DataTables。

谢谢阅读。

于 2021-08-07T09:46:29.750 回答