Datagridview全行选择但获取单元格值

54

我有一个全行选择的DataGridView。无论点击哪个单元格,我该如何仅获取特定单元格的数据,因为它会高亮显示整行。


18个回答

114
你可以这样做:
private void datagridview1_SelectionChanged(object sender, EventArgs e)
{
  if (datagridview1.SelectedCells.Count > 0)
  {
    int selectedrowindex = datagridview1.SelectedCells[0].RowIndex;
    DataGridViewRow selectedRow = datagridview1.Rows[selectedrowindex];  
    string cellValue = Convert.ToString(selectedRow.Cells["enter column name"].Value);           
  }
}

太好了 - 在找到这篇文章时花费了很多时间。 - hbk
@pratap K,DataGridView1_SelectionChanged事件会在窗体加载时触发吗?但在我的情况下确实发生了。请帮我解决这个问题。如果需要更多细节,我会发布一个问题。 - Sanjeev4evr
我想要相反的行为,而你发布的帮助了我意识到我需要做什么。SelectedCells.Count == 1 :) - Mido
谢谢你。非常棒的回答。 - SCramphorn

25

如果你想获取选定单元格的内容,你需要知道行和列的索引。

int rowindex = dataGridView1.CurrentCell.RowIndex;
int columnindex = dataGridView1.CurrentCell.ColumnIndex; 

dataGridView1.Rows[rowindex].Cells[columnindex].Value.ToString();

9

我知道有点晚了,但我想为您做出贡献。

这句话和IT技术无关。
DataGridView.SelectedRows[0].Cells[0].Value

这段代码就像吃蛋糕一样简单。


3
只晚了6年半! - Mark

8
在CellClick事件中,您可以编写以下代码。
string value =
      datagridviewID.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue.ToString();

使用以上代码,您将获得您点击的单元格的值。如果您想要获取点击行中特定列的值,请将 e.ColumnIndex 替换为您想要的列索引。


这是更好的答案,只需要将 e.ColumnIndex 更改为特定的字符串列名称或索引,因为问题要求如此。 - Ankush Madankar

5

您可以获取单元格的值,因为当前选择是在CurrentRow下引用的。

dataGridView1.CurrentRow.Cell[indexorname].FormattedValue

在这里,您可以使用索引或列名获取值。


2

我想指出,你可以使用.selectedindex让代码更加简洁。

string value = gridview.Rows[gridview.SelectedIndex].Cells[1].Text.ToString();


2
string value = dataGridVeiw1.CurrentRow.Cells[1].Value.ToString();

1

仅需使用: dataGridView1.CurrentCell.Value.ToString()

        private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
        }

或者

 // dataGrid1.Rows[yourRowIndex ].Cells[yourColumnIndex].Value.ToString()

 //Example1:yourRowIndex=dataGridView1.CurrentRow.Index (from selectedRow );
 dataGrid1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString()

 //Example2:yourRowIndex=3,yourColumnIndex=2 (select by programmatically )
  dataGrid1.Rows[3].Cells[2].Value.ToString()

1

这会让我得到数据网格视图中精确单元格的文本值。

private void dataGridView_SelectionChanged(object sender, EventArgs e)
    {
        label1.Text = dataGridView.CurrentRow.Cells[#].Value.ToString();
    }

你可以在标签中看到它,并将#更改为您想要的确切单元格的索引。

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