温馨提示×

怎么使用datagridview获取某行某列的值

小亿
384
2023-08-10 04:10:27
栏目: 编程语言

要使用DataGridView获取某行某列的值,可以通过以下步骤实现:

  1. 确定要获取值的行和列的索引。行的索引通常是DataGridView的SelectedCells属性中的第一个元素的行索引,列的索引可以是DataGridView中要获取值的列的索引。
int rowIndex = dataGridView.SelectedCells[0].RowIndex;
int columnIndex = dataGridView.Columns["ColumnName"].Index;
  1. 使用索引获取对应的单元格对象。
DataGridViewCell cell = dataGridView.Rows[rowIndex].Cells[columnIndex];
  1. 获取单元格的值。
string value = cell.Value.ToString();

完整的代码示例:

int rowIndex = dataGridView.SelectedCells[0].RowIndex;
int columnIndex = dataGridView.Columns["ColumnName"].Index;
DataGridViewCell cell = dataGridView.Rows[rowIndex].Cells[columnIndex];
string value = cell.Value.ToString();

注意:如果你想要获取的列的名称是已知的,也可以直接使用列的名称来获取列的索引,而不是通过列的Index属性来获取。

0