.net 右键单击以选择datagridview行
如何在右键单击上选择datagridview行?最酷的事情是在右键单击上添加一个菜单,例如带有“查看客户信息”、“验证上次发票”、“向该客户添加日志条目”等选项.net 右键单击以选择datagridview行,.net,datagridview,.net,Datagridview,如何在右键单击上选择datagridview行?最酷的事情是在右键单击上添加一个菜单,例如带有“查看客户信息”、“验证上次发票”、“向该客户添加日志条目”等选项 // Clear all the previously selected rows foreach (DataGridViewRow row in yourDataGridView.Rows) { row.Selected = false; } // Get the selected
// Clear all the previously selected rows
foreach (DataGridViewRow row in yourDataGridView.Rows)
{
row.Selected = false;
}
// Get the selected Row
DataGridView.HitTestInfo info = yourDataGridView.HitTest( e.X, e.Y );
// Set as selected
yourDataGridView.Rows[info.RowIndex].Selected = true;
您只需要添加一个ContextMenuStrip对象,添加菜单项,然后在DataGridView属性中选择它的ContextMenuStrip
这将在用户使用所有选项右键单击的行中创建一个新菜单,然后您需要做的就是变魔术:)
请记住,您需要JvR代码来获取用户所在的行,然后抓取包含客户机ID的单元格并传递该信息
希望它有助于改进您的应用程序
您可以在DataGridView的MouseDown事件中使用JvR的代码。将
DataGridView
子类化,并为网格创建MouseDown
事件
private void SubClassedGridView_MouseDown(object sender, MouseEventArgs e)
{
// Sets is so the right-mousedown will select a cell
DataGridView.HitTestInfo hti = this.HitTest(e.X, e.Y);
// Clear all the previously selected rows
this.ClearSelection();
// Set as selected
this.Rows[hti.RowIndex].Selected = true;
}
使其行为类似于鼠标左键?e、 g
private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex];
}
}
你必须做两件事:
I=e.RowIndex
DataGridView1.CurrentRow不会返回以前选择的行(这非常危险)。因为CurrentRow是只读的,所以您必须执行以下操作
Me.CurrentCell=Me.Item(e.ColumnIndex,e.RowIndex)
从
@Alan Christensen
代码转换为VB.NET
Private Sub dgvCustomers_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvCustomers.CellMouseDown
If e.Button = MouseButtons.Right Then
dgvCustomers.CurrentCell = dgvCustomers(e.ColumnIndex, e.RowIndex)
End If
End Sub
我在VS2017上接受测试,它为我工作
If e.Button = MouseButtons.Right Then
DataGridView1.CurrentCell = DataGridView1(e.ColumnIndex, e.RowIndex)
End If
代码也在VS2019中工作如果DataGridView的MultiSelect设置为false,则不需要清除以前的选择。此外,HitTestInfo可以返回HitTestInfo。如果命中不是有效的行/列,则不会返回HitTestInfo。无法。清除选择有助于加快速度?这比JvR的答案更灵活、更完整,但如果用户右键单击标题,则应添加检查
e.ColumnIndex>=0&&e.RowIndex>=0
。
If e.Button = MouseButtons.Right Then
DataGridView1.CurrentCell = DataGridView1(e.ColumnIndex, e.RowIndex)
End If