什么 WinForm 控件可以绑定列表(T)?
-
21-08-2019 - |
题
我一直致力于让我的项目保持面向对象。目前,我正在使用一个 .DLL,它将所有应用程序的类提供给 WinForms 项目作为表示层。
例如,我的 .DLL 将返回一个 SortableBindingList(Of T) 到表单中的代码。SortableBindingList(Of T) 来自 这里. 。我们假设有一个 SortableBindingList(Of Product)。假设.DLL的函数 Services.Products.GetList()
返回一个 SortableBindingList(Of Product),我可以轻松地执行此操作:
DataGridView1.DataSource = Services.Products.GetList()
现在,DataGridView 已正确填充我的产品列表。美好的。但是,没有 .SelectedItem 属性可以返回在 DataGridView 中选择的对象:
' Doesn't exist!
Dim p As Product = DataGridView1.SelectedItem
' Need to make another DB call by getting the Product ID
' from the proper Cell of the DataGridView ... yuck!
然而,ComboBox 或 ListBox 实际上会完整地存储和返回我的 Product 对象:
' Valid!
ComboBox1.DataSource = Services.Products.GetList()
Dim p as Product = ComboBox1.SelectedItem
然而另一个...ComboBox 和 ListBox 不显示 Product 对象的所有字段,仅显示 DisplayMember 属性的值。
VB.NET 2008 中是否有一个我所缺少的很好的控件,它为我提供了我想要的面向对象的功能,该功能将实际显示整个对象的字段,并在用户选择时返回该对象?我不知道为什么不会有。
解决方案
听起来您正在寻找 DataGridView 的 SelectedRows 属性. 。您应该能够将其用于您所描述的内容。
您可以使用它来获取 DataBoundItem,然后将其转换为原始类。假设我有一个绑定的 Product 对象列表,我会使用类似的东西:
Dim p As Product = CType(dataGridView1.SelectedRows(0).DataBoundItem, Product)
MessageBox.Show(p.Name & " " & p.Price)
如果选择整行,则此方法有效,否则可能会出现空引用异常。在这种情况下,您可以通过以下方式获取当前选定单元格的 RowIndex:
dataGridView1.SelectedCells(0).RowIndex
所以现在看起来像这样:
If dataGridView1.SelectedCells.Count > 0 Then
Dim index as Integer = dataGridView1.SelectedCells(0).RowIndex
Dim p As Product = CType(dataGridView1.SelectedRows(index).DataBoundItem, Product)
MessageBox.Show(p.Name & " " & p.Price)
End If
编辑: 更新为VB.NET