Accessing GridView Cells Value
I am trying to access the integer value of the first cell but I'm getting this error:
Unable to cast object of type 'System.Web.UI.WebControls.DataControlFieldCell' to type开发者_开发知识库 'System.IConvertible'.
And the value i have stored in that cell is an ID like 810
My Code
int myID = Convert.ToInt32(GridView1.Rows[rowIndex].Cells[0]);
Cells[0]
returns a DataControlFieldCell
object, not the cell's value.
Use the cell's Text
property.
GridView1.Rows[rowIndex].Cells[0].Text
--or--
GridView1.Rows[rowIndex].Cells[0].Value
Makes programmer's life harder with these stupid ambiguities introduced by Microsoft over time.
Try this both of this codes are valued
int SB = Convert.ToInt32(gdTest.SelectedRow.Cells[1].Text);
---------OR-------
int AS = Convert.ToInt32(gdTest.Rows[1].Cells[1].Text);
The recommended approach to retrieve the value of a cell in GridView/FormView is to use ExtractValuesFromCell() method. See an example below:
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"]
}
The returned values are strings and can be converted with the help of System.Convert class.
精彩评论