访问GridView单元格值

本文关键字:单元格 GridView 访问 | 更新日期: 2023-09-27 18:09:35

我试图访问第一个单元格的整数值,但我得到这个错误:

无法强制转换类型为"System.Web.UI.WebControls"的对象。"DataControlFieldCell"类型为"System.IConvertible"。

我存储在单元格中的值是一个ID,比如810

我的代码
int myID = Convert.ToInt32(GridView1.Rows[rowIndex].Cells[0]);

访问GridView单元格值

Cells[0]返回DataControlFieldCell对象,而不是单元格的值。
使用单元格的Text属性

GridView1.Rows[rowIndex].Cells[0].Text

——或

GridView1.Rows[rowIndex].Cells[0].Value

随着时间的推移,微软引入了这些愚蠢的歧义,使程序员的生活变得更加困难。

试试这两个代码都有值

 int SB = Convert.ToInt32(gdTest.SelectedRow.Cells[1].Text);
              ---------OR-------
int AS = Convert.ToInt32(gdTest.Rows[1].Cells[1].Text);

在GridView/FormView中检索单元格值的推荐方法是使用ExtractValuesFromCell()方法。请看下面的例子:

foreach(var row in GridView.Rows) 
{
    // retrieve all cell values in a row as a ordered dictionary.
    IOrderedDictionary cellValues = new OrderedDictionary();
    foreach(DataControlFieldCell cell in row.Cells)
    {      
            cell.ContainingField.ExtractValuesFromCell(cellValues, cell, row.RowState, true);
    }
    // now do something with the cellValues for e.g read the columns value
    // like - cellValues["EmployeeName"]
}

返回值是字符串,可以在System的帮助下进行转换。转换类。