当前位置: 代码迷 >> VB Dotnet >> DataGridView数据源可以绑定自定义的类吗解决思路
  详细解决方案

DataGridView数据源可以绑定自定义的类吗解决思路

热度:429   发布时间:2016-04-25 02:25:20.0
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

可以将DataSourceA类的实例绑定到DataGirdView中吗?
DataSourceA类需要实现什么接口吗?

我用下面的代码试过,没有任何反应。

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


------解决方案--------------------
dgv2.DataSource = new List().Add(New DataSourceC() With {.Col1 = "col1"}))
  
*****************************************************************************
签名档: http://feiyun0112.cnblogs.com/
  相关解决方案