访问GridView单元格值

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

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

我存储在该单元格中的值是一个像810的ID

我的代码

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

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 eg read the columns value // like - cellValues["EmployeeName"] } 

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