views:

24

answers:

1

What is a graceful/proper way to retrieve the Linq entity behind the selected row of a DataGridView? I am populating my DataGridView like this in the form Load event:

this.Database = new MyAppDataContext();
var userList = from c in this.Database.Users
                       orderby c.LastName
                       select c;
        this.gridUserList.DataSource = userList;

Then, in the DoubleClick event of the form I am doing this:

        int userPK = Convert.ToInt32(this.gridUserList.CurrentRow.Cells["colUserPK"].Value);
        var user = (from c in this.Database.Users 
                    where c.UserPK == userPK select c).First() ;
        //Do something with user object

It seems like there should be a more elegant way of getting the user row that was double-clicked on.

A: 

Here is the best option I have found:

var selectedUser = (User)this.gridUserList.CurrentRow.DataBoundItem;

Another option if you are using a BindingSource is:

var selectedUser = (User)this.userBindingSource.Current;
Alvin S