如何在选中改变时获取DataGridView中的特定单元格

3

使用列表框,我有以下代码来提取所选项目:

    private void inventoryList_SelectedIndexChanged(object sender, EventArgs e)
    {
        String s = inventoryList.SelectedItem.ToString();
        s = s.Substring(0, s.IndexOf(':'));
        bookDetailTable.Rows.Clear();
        ...
        more code
        ...
    }

我希望对于DataGridView做类似的事情,也就是当选择改变时,检索所选行中第一个单元格的内容。问题是,我不知道如何访问该数据元素。
非常感谢任何帮助。
2个回答

15

我认为这就是你在寻找的内容。如果不是的话,希望它能给你一个起点。

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    //User selected WHOLE ROW (by clicking in the margin)
    if (dgv.SelectedRows.Count> 0)
       MessageBox.Show(dgv.SelectedRows[0].Cells[0].Value.ToString());

    //User selected a cell (show the first cell in the row)
    if (dgv.SelectedCells.Count > 0)
        MessageBox.Show(dgv.Rows[dgv.SelectedCells[0].RowIndex].Cells[0].Value.ToString());

    //User selected a cell, show that cell
    if (dgv.SelectedCells.Count > 0)
        MessageBox.Show(dgv.SelectedCells[0].Value.ToString());
}

我认为是对的,但是我如何将我的 DataGridTable.SelectionChanged 与我个人的 SelectionChanged 方法链接起来(就像您上面写的那个方法一样)? - Elie
我不确定我理解你的意思。你是在问如何让控件调用该函数吗?使用VS设计器(点击控件并获取属性)或将以下代码放入构造函数中:this.dataGridView1.SelectionChanged += new System.EventHandler(this.dataGridView1_SelectionChanged); - Mitchell Gilman
(其中“dataGridView1”是您的数据网格的名称) - Mitchell Gilman
谢谢,我对VS设计器还不熟悉。当我双击控件时,它创建了CellContentClick方法,但我无法搞清楚如何创建SelectionChanged方法。 - Elie
没问题,我很高兴它起作用了。 :-) 顺便说一句,在VS设计师中,当你点击一个控件时,请查看属性窗口。点击窗口顶部的橙色闪电图标。这将显示所有可用事件的列表。 双击其中一个以添加它。 - Mitchell Gilman

0

使用列名是另一种解决这个问题的方法。

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
   var senderGrid = (DataGridView)sender;
   if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
   {
      if (e.ColumnIndex == dataGridView1.Columns["ColumnName"].Index)
      {
        var row = senderGrid.CurrentRow.Cells;
        string ID = Convert.ToString(row["columnId"].Value); //This is to fetch the id or any other info
        MessageBox.Show("ColumnName selected");
      }
   }
}

如果您需要传递所选行的数据,可以通过以下方式将其传递到其他表单。
Form2 form2 = new Form2(ID);
form2.Show();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接