如何将表格控件添加到表单?

时间:2012-08-22 06:51:40

标签: c# vb.net c#-4.0 c#-3.0

我想在表单中添加一个表,表包含2列和3行.3行是Name,Age和Place.In这个表在运行时我希望更新第2列中的值对于受尊重的行。 我想添加这样的表

enter image description here

对于eg.In上面的图像Name是column1中的表行项目之一,而column2中的第一行包含Name的值。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

创建某种容器类(即某种集合),用于存储键值对,并在运行时将它们绑定到DataGrid


Quick'n'dirty示例:

Class Container
    Inherits BindingList(Of Value)

    Class Value
        Public Property Key As String
        Public Property Value As Object
    End Class

    Public Sub New()
        Add(New Value With {.Key = "Name"})
        Add(New Value With {.Key = "Age"})
        Add(New Value With {.Key = "Place"})
    End Sub

    Default Public Overloads Property Item(ByVal key As String) As Object
        Get
            Return Me.FirstOrDefault(Function(v) v.Key = key)
        End Get
        Set(ByVal value As Object)
            Dim v = Me.FirstOrDefault(Function(e) e.Key = key)
            If v Is Nothing Then
                Add(New Value With {.Key = key, .Value = value})
            Else
                v.Value = value
            End If
        End Set
    End Property

End Class

Form

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim grd = New DataGrid With {.Dock = DockStyle.Fill}
    Controls.Add(grd)
    Dim container = New Container()

    grd.DataSource = container

    container("Age") = 12
    container("Place") = "Somewhere"
End Sub

enter image description here


然后你必须调整你的DataGrid的外观,这取决于你。

这样,网格就绑定到container对象,您可以轻松地读取/更改值。

答案 1 :(得分:-1)