DataGridView数据源可以绑定自定义的类吗
在窗口上有一个DataGirdView控件,我不想绑定DataTable中的数据,想绑定自定义类中的数据,这样可以吗?
例如:
DataGridView中只有一个名为Col1的列。
下面有两个类,DataSourceC和DataSourceA。
DataSourceC中的Col1属性值就是为了绑定到DataGirdView中的Col1列的。
DataSourceA是DataSourceC的数组。代码如下:
Public Class DataSourceC
Private _col1 As String
Public Property Col1() As String
Get
Return _col1
End Get
Set(value As String)
_col1 = value
End Set
End Property
End Class
Public Class DataSourceA
Dim _ds As List(Of DataSourceC)
Public Sub New()
_ds = New List(Of DataSourceC)()
End Sub
Public Sub Add(ByVal item As DataSourceC)
If item Is Nothing Then
Return
End If
_ds.Add(item)
End Sub
Public Property Item(ByVal index As Integer) As DataSourceC
Get
Return _ds(index)
End Get
Set(value As DataSourceC)
_ds(index) = value
End Set
End Property
End Class
Dim ds As New DataSourceA
ds.Add(New DataSourceC() With {.Col1 = "col1"})
dgv2.DataSource = ds
For Each item In dgv.Columns
CType(item, DataGridViewColumn).DataPropertyName = "Col1"
Next item