数据网格视图选择单元格值如何获取它
问题描述:
我想在Click事件中选择DataGridView Cell值我使用此代码会产生错误
i Want to get DataGridView selected Cell value on click event i use this code its generates a error
DataGridViewRow dgvrows = TrGrid.SelectedRows;
string c = dgvrows.Cells("Late_Time").value.toString();
答
DataGridView有一个 CurrentCell属性 [ ^ 。我认为这就是选定单元格的含义。如果你想查看所有选中的单元格,它有一个可枚举的SelectedCells属性来给出单元格对象。
DataGridView has a CurrentCell property[^]. I think that is what you mean by 'selected cell'. If you want to look at all the selected cells, it has a SelectedCells property which is enumerable to give cell objects.
下面这段代码可以帮到你:
The following piece of code will do the trick for you:
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
}
}
希望这能帮到你。
Hope this will help you out.
SelectedRows
将返回DataGridViewSelectedRowCollection
类型的行集合,而不是DataGridViewRow
。
所以你可以像这样使用它:
SelectedRows
will return a collection of rows of typeDataGridViewSelectedRowCollection
and notDataGridViewRow
.
So you can use it like this :
DataGridViewSelectedRowCollection rows = dataGridView1.SelectedRows;
string val =(string)rows[2].Cells["Late_Time"].Value; //I have specified rowIndex as 2 as an example