2011-08-24 53 views
1

你有一个伪表类和一个伪行类。该行有点通用,没有强类型的字段。它遵循典型的字典界面将字典绑定到WinForms网格(或组合)?

Dim age As Object = person("Age") 'accessed via default property Item 

VS

Dim age As Integer = person.Age 'an actual property typed as an Integer 

什么模式使用,因此,我们可以把我们的伪表和它的行绑定到一个网格或组合框?

Dim rs As New clsResultSet(tblPeople) 
Dim id As Object = rs(0)("Id") '913 
Dim name As Object = rs(0)("Name") 'Ted 
Dim age As Object = rs(0)("Age") '43 
Dim occupation As Object = rs(0)("Occupation") 'cab driver 

grd.DataSource = rs 'In grid I expect to see Name, Age, Occupation columns 

cbo.DataSource = rs 
cbo.DisplayMember = "Name" 'could we do this? 
cbo.ValueMember = "Id" '...and this? 

我读了所有有关的IList,IBindingList的,BindingSource的,等等,尝试了一些东西,我仍然令人费解如何得到这个权利。我发现的大多数例子都希望你的记录对象具有强类型(例如person.Age而不是person(“Age”))。

这里有一些简单的类入手:

Public Class clsResultSet 'Like a DataTable 
    Inherits List(Of clsRecord) 

    Private mdicFields As New Dictionary(Of String, Object) 

    Public Sub New(vdt As DataTable) 'Loaded from table 
     For Each bdc As DataColumn In vdt.Columns 
      Me.mdicFields.Add(bdc.ColumnName, bdc) 
     Next 
     For Each vdr As DataRow In vdt.Rows 
      Me.Add(New clsRecord(vdr, Me)) 
     Next 
    End Sub 

    Public ReadOnly Property Fields As Dictionary(Of String, Object) 
     Get 
      Return Me.mdicFields 
     End Get 
    End Property 
End Class 

Public Class clsRecord 'Like a DataRow 
    Inherits Dictionary(Of String, Object) 
    Private mrs As clsResultSet 

    Protected Friend Sub New(vdr As DataRow, vrs As clsResultSet) 
     Me.mrs = vrs 
     For Each bPair As KeyValuePair(Of String, Object) In vrs.Fields 
      Me.Add(bPair.Key, vdr(bPair.Key)) 
     Next 
    End Sub 
End Class 

这个问题,如问,得到的回答。因为我没有得到我的问题的根源,我reframed it

+0

你正在使用哪个VB版本? –

回答

0

据我所知,没有办法直接绑定到字典对象。这是一个快速解决方法,用于固定DataSource的组合框。创建使用选择和匿名对象所需性质的新的列表(与Visual Studio 2008和较新的作品):

Dim rs As New clsResultSet(tblPeople) 
cbo.DataSource = rs.Select(Function(x) New With {.Name = x("Name"), .Id = x("Id")}).ToList() 
cbo.DisplayMember = "Name" 
cbo.ValueMember = "Id" 

我想你可以使用类似的方法绑定到一个DataGridView,但我会建议使用而不是强类型类(具有属性名称,年龄等的Person类),除非它是只读的 - 不会更改的DataGridView。

编辑:

你可能会感兴趣的DataGridView.DataSource文档的备注部分。基本上数据源可以是IList,IListSource,IBindingListIBindingListView。 DataTable和DataSet类实现IListSource,因此可能值得尝试为您自己的类实现此接口。

+0

感谢您的快速反馈。有趣的是本地DataRow具有匿名列(例如字典式访问列值)。基本上我试图创建一个自定义的DataRow/DataTable/DataSet来帮助实施店铺标准。 – Mario

+0

看我的编辑.... –

+0

糟糕。我已经重新提出了这个问题(因为你的确按照我的要求回答了)。现在看到帖子中的交联。我在注意到你的编辑之前做了这个。我一定会阅读你提供的内容,因为我有时间。感谢一群帮助。 – Mario