Accessing properties of SelectedRow during SelectedIndexChanged event in dynamically generated GridView
<p>I have an empty GridView object on a page that I bind to a LINQ qry result at run time.  The GridView has a 'Select" button that fires the SelectedIndexChanged event and it's inside of this event that I'd like to access the data of one of the fields in the selected row.</p>

<p>So far, I can only find one way to do this, and it seems suboptimal:</p>

<pre><code>protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
  GridViewRow row = GridView2.SelectedRow;
  string UserID = row.Cells[1].Text;
  //Do stuff with the userID
}
</code></pre>

<p>So this just access the cell data directly based on the cell index.  The UserID just happens to be in the second cell and so it works.  But later down the road, the UserID may not be in that same column.  It seems like I'd be better off looking up the value of this cell by accessing by the cell's header name, or by any method other than the cell index itself.</p>

<p>Any ideas?</p>

<p>Thanks!</p>
