tags:

views:

26

answers:

2

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.

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

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

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.

Any ideas?

Thanks!

A: 

Try this


User user = (User)((DataRowView)row.DataBoundItem).Row;
int userID = user.UserID;

I am assuming you have a class called User and you are binding the DataGridView to may a List

sh_kamalh
The GridView data source is a linq query the selects into an anonymous type. Maybe I don't need to use an anonymous type in the select though, I can try it another way...
Elbelcho
try var user = (User)((DataRowView)row.DataBoundItem).Row; then int userID = user.UserID;
sh_kamalh
A: 

I don't know much about asp.net, but in the C# DataGridView you can index columns directly by column name, i.e.

string UserID = row.Cells["UserID"].Text;

or something like that. Might be worth a try.

bde
Apparently the WebUI version of a GridView only accepts an integer index for Cells. :(
Elbelcho