【问题标题】:What WinForm Control To Bind List(Of T)?什么 WinForm 控件绑定 List(Of T)?
【发布时间】:2009-07-01 17:50:20
【问题描述】:

我一直致力于为我的项目保持面向对象的东西。目前,我正在使用一个 .DLL,它将所有应用程序的类提供给充当表示层的 WinForms 项目。

例如,我的 .DLL 将返回一个 SortableBindingList(Of T) 以在表单中编码。 SortableBindingList(Of T) 来自here。让我们假设一个 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 中是否有一个我只是缺少的不错的控件,它为我提供了我想要的面向对象的功能,它实际上将显示整个对象的字段并在用户选择时返回该对象?我不知道为什么没有。

【问题讨论】:

    标签: vb.net winforms oop presentation-layer


    【解决方案1】:

    听起来您正在寻找 DataGridView 的 SelectedRows property。您应该能够将其用于您所描述的内容。

    您使用它来获取 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

    【讨论】:

    • 不,.SelectedRows 属性返回一个 DataGridViewRow 类型的对象,而不是最初绑定到 DataGridView 的对象。
    • 更新了答案。您可以使用它来获取数据绑定对象,然后对其进行适当的转换。
    猜你喜欢
    • 2010-09-28
    • 2013-05-17
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多