我在将对象数据绑定到 VB.NET(VS2008/.NET 3.5)中的组合框时遇到问题。请看一下我的代码的简化版本:
Friend Class clDocument
Private _items as New List(Of clDocumentItems)
<System.ComponentModel.DisplayName("Items")> _
<System.ComponentModel.Bindable(True)> _
Public Property Items() As List(Of clDocumentItems)
Get
Return _items
End Get
Set(ByVal value As List(Of clDocumentItems))
_items = value
RaiseEvent ItemsChanged(Me, New EventArgs)
End Set
End Property
Public Event ItemsChanged As EventHandler
End Class
Friend Class clDocumentItems
Private _uid as String = ""
Private _docnumber as String = ""
<System.ComponentModel.DisplayName("UID")> _
<System.ComponentModel.Bindable(True)> _
Public Property UID() As String
Get
Return _uid
End Get
Set(ByVal value As String)
_uid = value
RaiseEvent UIDChanged(Me, New EventArgs)
End Set
End Property
<System.ComponentModel.DisplayName("Document")> _
<System.ComponentModel.Bindable(True)> _
Public Property DocNumber() As String
Get
Return _docnumber
End Get
Set(ByVal value As String)
_docnumber = value
RaiseEvent DocNumberChanged(Me, New EventArgs)
End Set
End Property
Public Event UIDChanged As EventHandler
Public Event DocNumberChanged As EventHandler
End Class
在其他地方,我们得到了以下代码:
Private Sub cmd_go_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmd_go.Click
'Try to load the object with data, this works well
Dim _document as New clDocument
_document.Load(somevalue)
cmb_docs.DataSource = Nothing
cmb_docs.Items.Clear()
If _document.UID = "" Then Exit Sub 'Object wasn't loaded so get out
'Create the binding.
cmb_docs.ValueMember = "UID"
cmb_docs.DisplayMember = "DocNumber"
cmb_docs.DataSource = _document.Items
End Sub
现在,问题是 ComboBox 填充了与 _document.Items 中的对象一样多的项目,但它不传递真实数据 - 组合框填充了“Namespace.clDocumentItems”字符串。请注意,当绑定到常规类属性(字符串、整数等)时,类似的代码可以完美运行。
现在,我可以通过使用调试器的反射来猜测这是因为 Datsource 正在接收对象列表而不是字段,但是我不知道如何避免这种情况,而不必创建另一个数组或列表只有这些值并将其传递给 Datasource 属性...
我探索了该网站以寻找类似的东西,唯一接近的是这个3 年前没有回答的问题,所以我希望今天有更好的运气;)
谢谢你的时间!
编辑:下面我按照评论中的要求将用于数据绑定的代码添加到 DataGridView。
Private WithEvents _bs as New BindingSource
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.AutoGenerateColumns = False
Dim column As DataGridViewColumn = New DataGridViewTextBoxColumn()
column.DataPropertyName = "Document"
column.Name = "colDoc"
DataGridView1.Columns.Add(column)
_bs.DataSource = _document.Items
Me.DataGridView1.DataSource = _bs
End Sub