2010-07-07 54 views
1

在DataGridView的选定行背后检索Linq实体的优雅/正确的方法是什么? 我填充我的DataGridView这样的形式Load事件:从Linq到Linq的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 

看起来应该有一个更获得双击用户行的优雅方式。

+0

你的问题是什么?你是否遇到异常?你想用用户对象做什么?请与我们分享更多信息。 – 2010-07-08 06:54:43

+0

我看到的问题是我无法以干净,强类型,面向对象的方式到达选定的用户对象。一种理论上改进的方法是在表单上拥有一个UserList属性,该属性是Linq查询对象。即“this.UserList = from this.Database.Users .....”等,并将网格数据源设置为this.UserList。然后在DoubleClick事件中,可以说“var User = UserList.CurrentEntity”或“var User = UserList.SelectedEntity”或类似的东西。无论如何,我是Linq的新手,仍在学习和研究,并寻找意见。 – 2010-07-08 13:25:16

回答

5

这里是我发现最好的选择:

var selectedUser = (User)this.userBindingSource.Current; 
1

我已经绑定MyDataSourceTabledataGridView1

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

另一种选择,如果你正在使用的BindingSource是。 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子句:使用上述发布应答,在数据源中的相应条目仅由一个一行代码引用。阿尔文S的回答非常直接和简洁。这很有价值。