我一直在使用 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 行中获取正确的类型,以便该方法再次开始工作,但到目前为止还没有运气。谁能指出我正确的方向。
非常感谢。