"Neil" <> wrote in message
news: oups.com...
>I have a gridview which is being populated with no problems.
>
> I want to be able to reference the data from the cells in the row but
> having followed an example on MSDN cannot get any data to be displayed
> in a text box no matter which cell index I provide.
>
> I tried a row of code that successfully displays the rowindex of the
> selected row.
>
> The code with comments is below:
>
> protected void GridView1_SelectedIndexChanged(object sender,
> EventArgs e)
> {
> // Get the currently selected row using the SelectedRow
> property.
> GridViewRow row = GridView1.SelectedRow;
>
> //This row doesn't put anything in the text box (code copied
> from MSDN)
> TextBox2.Text = row.Cells[2].Text;
>
> //This row (when not commented out and line above commented
> out) puts the row index in the text box
> //TextBox2.Text = GridView1.SelectedRow.RowIndex.ToString();
> }
>
> Can anyone provide me with the code that will allow me to access the
> data in each cell. When working in the debugger I'm being told that
> the text value is an empty string which can't be correct coz i can see
> the value in the grid. I'm new to both ASP.Net & C# so may be doing
> something obviously wrong!
>
> Thanks
>
This works for me:
//////////////////////////////////////////////////////////////
//Use this method to copy the items in the GridViewRowCollection
object
//into the specified System.Array object, starting at the specified
index.
//The System.Array object can then be used to access the items in
the collection.
// Copy the items in the Rows collection into an array.
GridViewRow[] rowArray = new GridViewRow[gv.Rows.Count];
gv.Rows.CopyTo(rowArray, 0);
// Iterate though the array and display the value in the first cell
of the row.
int j = -1;
foreach (GridViewRow row in rowArray)
{
j++;
if (j == idx)
{
Label1.Text = row.Cells[1].Text;
}
}
//////////////////////////////////////////////////////////////
Apparantly the key is to copy the rows into an array to be able to iterate
through it.
I got the basic idea from :
http://msdn2.microsoft.com/en-us/lib...ollection.aspx
-Fred