65.9K
CodeProject 正在变化。 阅读更多。
Home

为 IList 对象调整 DataGridTableStyle

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (1投票)

2009年3月20日

CPOL
viewsIcon

23200

为 IList 对象设置 DataGridTableStyle 的成员名称属性。

引言

如果 DataGridTableStyle 的成员名称属性未正确设置,DataGrid 对象将始终使用自动生成的默认布局。在使用 DataSet 时,您可以分配已知的表名,但对于 IList 对象,其工作方式略有不同。IList 的名称是在运行时生成的。

使用代码

我添加了一个简单的代码示例,您可以将其粘贴到您的项目中。诀窍是在运行时使用 mlstPersons.GetType.Name 获取列表对象的名称。

Public Class Form1
    Private mlstPersons As New List(Of person)

    Private Sub MenuItem1_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MenuItem1.Click
        Application.Exit()
    End Sub

    Private Sub MenuItem2_Click(ByVal sender As System.Object, _
                ByVal e As system.EventArgs) Handles MenuItem2.Click
        ' Fill data
        mlstPersons.Add(New person("John", 39))
        mlstPersons.Add(New person("Jane", 33))

        DataGrid1.DataSource = mlstPersons
        DataGrid1.TableStyles.Clear()
        gridstyle(mlstPersons.GetType.Name)

    End Sub

    Private Sub gridstyle(ByVal mappingname As String)
        Dim ts As New DataGridTableStyle
        Dim cs As DataGridColumnStyle
        Dim i As Int16

        ts.MappingName = mappingname

        cs = New DataGridTextBoxColumn
        cs.HeaderText = "nAmE"
        cs.MappingName = "name"
        cs.Width = 100
        ts.GridColumnStyles.Add(cs)

        cs = New DataGridTextBoxColumn
        cs.HeaderText = "aGe"
        cs.MappingName = "age"
        cs.Width = 50
        ts.GridColumnStyles.Add(cs)

        i = DataGrid1.TableStyles.Add(ts)
    End Sub
End Class

Public Class person
    Private mName As String
    Private mAge As Integer

    Public Property name() As String
        Get
            Return mName
        End Get
        Set(ByVal value As String)
            mName = value
        End Set
    End Property

    Public Property age() As Integer
        Get
            Return mAge
        End Get
        Set(ByVal value As Integer)
            mAge = value
        End Set
    End Property

    Public Sub New(ByVal name As String, ByVal age As Integer)
        mName = name
        mAge = age
    End Sub
End Class
© . All rights reserved.