【问题标题】:DataGridView and Right ClickDataGridView 和右键单击
【发布时间】:2014-02-09 15:49:25
【问题描述】:

我有一个链接到 ContextMenuStrip 的 DataGridView。 DataGridView 已填充。我选择一行(任何单元格),当我右键单击时,它会打开一个菜单,我可以在其中选择编辑、重命名或删除。如何将所选行的行号传递给我的 ContextMenuStrip? 因此,我左键单击以选择第 2 行中的一个单元格。我右键单击 DataGridView 上的任意位置,然后选择“重命名”。 我想收到一条消息“您想重命名第 2 行”。可以直接右键单击第 2 行并获取消息(无需先选择第 2 行上的单元格)。这是我的代码尝试:

void RenameToolStripMenuItemClick(object sender, EventArgs e)
{ //this should rename the table
    MessageBox.Show("This should rename the selected row number " + dataGridView1.SelectedRows.ToString());
}

【问题讨论】:

  • 这是在 WPF 还是 Winforms 中?

标签: c# datagridview contextmenustrip


【解决方案1】:

您需要查看 DataGridView 的 CurrentCell 属性的 RowIndex 属性。类似的东西

void RenameToolStripMenuItemClick(object sender, EventArgs e)
{ //this should rename the table
    MessageBox.Show("This should rename the selected row number " + dataGridView1.CurrentCell.RowIndex);
}

但请记住 RowIndex 计数从 0 开始。

因此,第一行将显示第 0 行,第二行将显示第 1 行。

要解决 RowIndex 混淆问题,您只需将 1 添加到 rowIndex,如下所示

void RenameToolStripMenuItemClick(object sender, EventArgs e)
{ //this should rename the table
    MessageBox.Show("This should rename the selected row number " + (dataGridView1.CurrentCell.RowIndex + 1));
}

【讨论】:

  • 您也可以使用 dataGridView1.CurrentRow.Index,但这只是个人喜好。
  • 感谢 SQL.NET 勇士。我选择您的答案作为解决方案,因为它对我的需求最直接。另外,感谢 TylerD87 指出 CurrentRow 属性。
  • 这不是一个好的解决方案。如果网格处于全行选择模式,CurrentCell 不会返回有用的结果。
【解决方案2】:

在datagridview上添加事件:“MouseDown” 在表单中,创建一个全局整数变量;

        try
        {
            if (e.Button == MouseButtons.Right)
            {
                dtg_contatos.ClearSelection();
                var hti = dtg_contatos.HitTest(e.X, e.Y);
                dtg_contatos.Rows[hti.RowIndex].Selected = true;
                selected_row = hti.RowIndex;
            }
        }
        catch
        {
        }

现在,在 ContextMenuStrip 中添加 CLickEvent

        string verificacao = dtg_contatos.Rows[selected_row].Cells[0].Value.ToString();
        if (verificacao != "")
        {
            int codigo = int.Parse(dtg_contatos.Rows[selected_row].Cells[0].Value.ToString());
        }

我认为鳕鱼在第一个单元格上,然后您可以根据需要使用数据,一旦您拥有鳕鱼,您就可以做任何事情。

【讨论】:

  • 谢谢迪特里希。你的代码比 Warrior 的更复杂,我选择了更简单的方法。
【解决方案3】:

订阅DataGridView.CellMouseDown 事件。在事件处理程序中,显示所需的上下文菜单。

示例代码:

void myDGV_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            //get the rowindex or columnindex from the event argument and show the context menu.
        }
    }

【讨论】:

    猜你喜欢
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多