2010-01-18 44 views
33

我需要从da databound DataGridView中获取当前选定的对象。DataGridView获取当前选定的对象

我不需要当前选定单元格的对象,而是整个行所基于的对象,在这种情况下,这是一个BusinessObject whos属性用于生成网格的列。

我可以通过数据源,但它本身只是一个对象,可以是一个BindingSource或IBindingList或类似的东西 - 所以不容易的标准化的方式来获得想要的对象。

之后,需要检查名为IsChanged的属性的businessObject,并要求用户在bindingsource选择下一个项目之前保存或放弃更改。因此,我必须在DataGridView的RowValidating-Event内部找出当前对象,因为BindingSource不会在发生更改之前提供停止更改的事件。 See here for the well known problem

感谢您阅读;-)

回答

69

DataGridViewRow.DataBoundItem包含它绑定到 '生意' 的对象。

+4

你可以得到这样

yourDGV.CurrentCell.Value; 

选定单元格的值谢谢你正确提示我,有时候应该放松一下,放松一下,而不是更强烈地搜索...... – 2010-01-18 09:55:18

+1

这比缓存数据然后尝试使用th e选定的索引。谢谢! – styfle 2013-10-22 23:29:14

+0

只是想提一下,如果你的dataGrid没有“绑定”到数据上,这也是有效的,但是如果你刚刚应用了'DataSource' – copa017 2015-10-01 21:16:33

6

这里是我的代码把这个到您的Person类

public static explicit operator Person(DataRow dr) 
    { 
     Person p = new Person(); 
     p.adi = dr.ItemArray[0].ToString(); 
     p.id = Int32.Parse(dr.ItemArray[1].ToString()); 
     p.soyadi = dr.ItemArray[2].ToString(); 
     p.kartNo = dr.ItemArray[3].ToString(); 
     p.dogumTarihi = DateTime.Parse(dr.ItemArray[4].ToString()); 
     p.adres = dr.ItemArray[5].ToString(); 
     p.meslek = dr.ItemArray[6].ToString(); 
     p.telefon = dr.ItemArray[7].ToString(); 
     p.gsm = dr.ItemArray[8].ToString(); 
     p.eposta = dr.ItemArray[9].ToString(); 

     return p; 
    } 

,这是一个更新按钮点击

DataRow row = (dataGridView1.SelectedRows[0].DataBoundItem as DataRowView).Row; 
Person selected = (Person)row; 
0

怎么样这样?

foreach (DataGridViewRow item in this.dataGridView1.SelectedRows) 
{ 
    MessageBox.Show(item.Cells[0].Value.ToString()); 
} 

我们可以得到多个选定的行数据。

0

由于您确实声明了IBindingList - 是的,正如其他人所说的那样,DataBoundItem属性会给你你所需要的 - 这有一个问题,我以前经历过,并以空引用结束,但现在我不能想想它发生的场景。

如果您使用BindingSource进行数据绑定 - 您可以捕获BindingSource的CurrentChanged,CurrentItemChanged事件,那么您的B.O.不需要额外的IsChanged属性。 ..,底层数据源也可以指示修改 - 例如,如果您将BindingSource绑定到数据表,该行将为您提供修改标志。

1

如果你想在一个字符串形式的值只是使用的toString这样

yourDGV.CurrentCell.Value.toString(); 

这应该这样做

相关问题