Getting Entity Behind Selected Row From DataGridView with Linq To Sql
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["colUs开发者_StackOverflowerPK"].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.
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;
I have bind MyDataSourceTable
to dataGridView1
. The C# code looks like this:
List<MyDataSourceItem> MyDataSourceTable;
bs = new BindingSource();
bs.DataSource = MyDataSourceTable;
dataGridView1.DataSource = bs;
When the user of my program select a row on dataGridView1
, we know what row since we have the row index. Using the Answer in the above posting, the corresponding entry in the data source is referenced by just one single line of code:
private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count <= 0) return; // this line prevents exception
MyDataSourceItem mdsi = (MyDataSourceItem)this.dataGridView1.CurrentRow.DataBoundItem; // Alvin S
// mdsi now reference the corresponding object on the list
.
.
}
To safeguard exception being thrown on null
object, an if
clause is added. Alvin S's answer is very direct and sccinct. It is valuable.
精彩评论