5

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]);
sab669
  • 3,984
  • 8
  • 38
  • 75
user710502
  • 11,181
  • 29
  • 106
  • 161

4 Answers4

6

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

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
4
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.

Alexander
  • 2,320
  • 2
  • 25
  • 33
Bhaggya
  • 41
  • 1
  • 1
0

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);
tharinda
  • 9
  • 7
0

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.

Vijay Pant
  • 74
  • 1
  • 7
  • To elaborate, this way gives the old values stored when the gridview is originally binded/created, but not the new value typed into the input box when you are updating – Bbb Jul 13 '18 at 14:33