gpt4 book ai didi

c# - 在 mouse_click 事件中选择 DataGridView 中的行

转载 作者:行者123 更新时间:2023-11-30 13:47:28 24 4
gpt4 key购买 nike

我在表单上有一个 DataGridView。当我右键单击一行时,我需要程序打开上下文菜单。通过此上下文菜单,我希望能够修改 DataGridView 中的数据。

我已经获得上下文菜单以显示我右键单击的位置,但我不知道从这里去哪里。因为我将删除(例如)整行,所以我需要获取该行的索引并将其设置为选中状态。我在 cell_clicked 事件中尝试了此操作,但无法确定是否按下了鼠标左键或右键。但是对于 mouse_click 事件,我无法获取行索引。

这是我的代码:

public Form()
{
ContextMenu contextMenu = new ContextMenu();

//Fill Context Menu
MenuItem delete = new MenuItem("Delete");
contextMenu.MenuItems.Add(delete);
}

private void grdSchedules_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
contextMenu.Show(grdSchedules, new Point(e.Y, e.Y));
//Get rowindex here and select row
}
}

我试过这样:

 private void grdSchedules_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right) //e.Button does not work here
{
contextMenu.Show(grdSchedules, new Point(e.Y, e.Y));
}
}

最佳答案

我创建了一个更简单、更快速的通用方法,适用于任何数据网格。此方法允许通过右键单击来选择行。将此方法添加到 DataGridViews 的“MouseDown”事件中:

    public void DataGridView_RightMouseDown_Select(object sender, MouseEventArgs e)
{
// If the user pressed something else than mouse right click, return
if (e.Button != System.Windows.Forms.MouseButtons.Right) { return; }

DataGridView dgv = (DataGridView)sender;

// Use HitTest to resolve the row under the cursor
int rowIndex = dgv.HitTest(e.X, e.Y).RowIndex;

// If there was no DataGridViewRow under the cursor, return
if (rowIndex == -1) { return; }

// Clear all other selections before making a new selection
dgv.ClearSelection();

// Select the found DataGridViewRow
dgv.Rows[rowIndex].Selected = true;
}

关于c# - 在 mouse_click 事件中选择 DataGridView 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17197132/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com