使用Linq To Sql从DataGridView获取所选行后面的实体

时间:2010-07-07 22:05:27

标签: c# linq-to-sql datagridview

在DataGridView的选定行后面检索Linq实体的优雅/正确方法是什么? 我在表单Load event:

中填充我的DataGridView
this.Database = new MyAppDataContext();
var userList = from c in this.Database.Users
                       orderby c.LastName
                       select c;
        this.gridUserList.DataSource = userList;

然后,在我正在执行此操作的表单的DoubleClick事件中:

        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

似乎应该有一种更优雅的方式来获取双击的用户行。

2 个答案:

答案 0 :(得分:6)

答案 1 :(得分:1)

我已将MyDataSourceTable绑定到dataGridView1。 C#代码如下所示:

List<MyDataSourceItem> MyDataSourceTable;
bs = new BindingSource();
bs.DataSource = MyDataSourceTable;
dataGridView1.DataSource = bs;

当我的程序的用户在dataGridView1上选择一行时,我们知道因为我们有行索引所在的行。使用上述发布中的答案,数据源中的相应条目仅由一行代码引用:

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
    .
    .
}

为了防止在null对象上抛出异常,添加了if子句。 Alvin S的回答是非常直接和严谨的。这很有价值。