简体   繁体   English

如何在表格中添加表格控件?

[英]How to add a table control to the form?

I want to add a table to the form and table contains 2 columns and 3 rows.the 3 rows are Name,Age and Place.In this table at run time i want to update values in the 2nd column for the respected rows. 我想在表格中添加一个表,并且该表包含2列和3行。这3行是Name,Age和Place。在此表中,我想在运行时更新第二列中相关行的值。 I want to add table like this 我想这样添加表格

在此处输入图片说明

For eg.In above image Name is the one of the table row item in column1 and in column2 first row contains value of Name. 例如,在上图中,名称是列1中的表行项目之一,在列2中,第一行包含名称值。

How can i do it? 我该怎么做?

Create some kind of container class (that is some kind of collection) that stores your key-value pairs, and bind them to a DataGrid at runtime. 创建某种容器类(即某种集合)来存储您的键值对,然后在运行时将它们绑定到DataGrid


Quick'n'dirty example: 快速肮脏的例子:

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

In your Form : 在您的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

在此处输入图片说明


You then have to adjust the apperance of your DataGrid of course, it's up to you. 然后,您必须调整DataGrid的外观,这完全取决于您。

This way, the grid is bound to the container object, and you can read/change values easily. 这样,网格便被绑定到了container对象上,您可以轻松地读取/更改值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM