【问题标题】:Get datagrid values by row index for later use按行索引获取数据网格值以备后用
【发布时间】:2023-03-19 22:24:01
【问题描述】:

我正在尝试获取我单击的数据网格行的单元格的值并将它们存储以供以后使用,但似乎我无法让它工作。

单击该行应该会出现一个菜单,我可以在该菜单上选择使用这些值执行操作。

这就是我目前所取得的成就

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs x)
        {
            if (dataGridView1.Rows[x.RowIndex].Cells["Name"].Value != null) name = dataGridView1.Rows[x.RowIndex].Cells["Name"].Value.ToString();
            else if (dataGridView1.Rows[x.RowIndex].Cells["LastName"].Value != null) last = dataGridView1.Rows[x.RowIndex].Cells["LastName"].Value.ToString();
        }

        private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (last != null && name != null)
                {
                    ContextMenu cm = new ContextMenu();
                    this.ContextMenu = cm;
                    cm.MenuItems.Add(new MenuItem("&Do something with those values in this row", new System.EventHandler(this.do_Action_with_values)));
                    cm.Show(this, new Point(e.X, e.Y));
                }
                last = null;
                name = null;
            }
        }

删除:if (last != null && name != null)

将使菜单工作,但不保存值,它们都是空的。

是否有适当的方法将被点击行的所有列值存储在字符串中?

【问题讨论】:

  • 这似乎很复杂。每次我这样做时,我都只是将一个单击处理程序连接到 cm 项,并询问网格处理程序中的选定行/单元格。无法理解您为什么要使用鼠标向下显示菜单等;您可以添加一个上下文菜单并将其设置为属于网格..
  • 我倾向于同意@CaiusJard。您有一个鼠标按下处理程序来响应右键单击(应用程序上的任何位置),以及一个单独的单元格单击处理程序来设置值。右键单击处理程序也将值设置为 null。通过将所有代码放入一个处理程序来简化这一点 - 使用 CellMouseClick,它使用 DataGridViewCellMouseEventArgs,它包含单元格详细信息(行和列)和鼠标详细信息(鼠标右键),供您执行您希望使用的操作。那么你就不需要存储姓名/姓氏了,你可以立即读取单元格并对其进行操作。
  • @Chris 你能给我举个例子吗?我已经尽我所能,这就是我目前所能想到的

标签: c# datagrid


【解决方案1】:

对于 cmets 中的每个请求,使用 CellMouseClick 事件和 DataGridViewCellMouseEventArgs 将您的处理程序组合成一个具有您需要的所有属性的事件处理程序。

请注意,以下代码是在 IDE 之外编写的,因此可能存在语法/其他错误。

    private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        if (e.Button != MouseButtons.Right) return;
        int row = e.RowIndex;
        string name = dataGridView1.Rows[row].Cells["Name"].Value;
        string last = dataGridView1.Rows[row].Cells["LastName"].Value;
        if (name == null || name.Trim().Length == 0) return;
        if (last == null || last.Trim().Length == 0) return;
        ContextMenu cm = new ContextMenu();
        this.ContextMenu = cm;
        cm.MenuItems.Add(new MenuItem("&Do something with those values in this row", new System.EventHandler(this.do_Action_with_values)));
        cm.Show(this, new Point(e.X, e.Y));
    }

【讨论】:

    猜你喜欢
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    相关资源
    最近更新 更多