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
        ...
    }

I want to do something similar for a DataGridView, that is, when the selection changes, retrieve the contents of the first cell in the row selected. 问题是,我不知道如何访问该数据元素。

任何帮助是极大的赞赏。

4

2 回答 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());
}
于 2009-01-01T06:56:20.283 回答
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();
于 2018-02-03T05:17:00.293 回答