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]);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Cells[0] returns a DataControlFieldCell object, not the cell’s value.
Use the cell’s Text property.

Method 2

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.

Method 3

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);

Method 4

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x