新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

C#中如何使用datagridview获取某行某列的值,c# datatype

发布时间:2023-09-27 19:56:45

C#中如何使用datagridview获得某行某列的值

在C#中,可使用DataGridView的Rows和Columns属性来获得指定行和列的值。
首先,使用Rows属性获得指定行的DataGridViewRow对象,然后使用Cells属性获得该行中指定列的DataGridViewCell对象,最后使用Value属性获得该单元格的值。
以下是一个示例代码,演示怎样获得第2行第3列的值:

// 获得第2行第3列的值
var value = dataGridView1.Rows[1].Cells[2].Value;
// 将值转换成字符串
string strValue = value.ToString();

需要注意的是,行和列的索引都是从0开始的。在示例代码中,我们使用[1]获得第2行,使用[2]获得第3列的值。
另外,还可以根据DataGridView的列名来获得某行某列的值。可使用Columns属性来获得指定列的DataGridViewColumn对象,然后使用Index属性获得该列的索引,最后使用Cells属性获得指定行该列的DataGridViewCell对象。
以下是一个示例代码,演示如何根据列名获得第1行“列名”列的值:

// 获得第1行“列名”列的值
var columnName = "列名";
var columnIndex = dataGridView1.Columns[columnName].Index;
var value = dataGridView1.Rows[0].Cells[columnIndex].Value;
// 将值转换成字符串
string strValue = value.ToString();

在示例代码中,我们首先使用Columns属性获得“列名”列的DataGridViewColumn对象,然后使用Index属性获得该列的索引,最后使用Cells属性获得第1行该列的DataGridViewCell对象。