【问题标题】:How to add a table control to the form?如何在窗体中添加表格控件?
【发布时间】:2012-08-22 06:51:40
【问题描述】:

我想在表单中添加一个表,该表包含 2 列和 3 行。这 3 行是名称、年龄和地点。在运行时这个表中,我想更新第二列中受尊重行的值. 我想添加这样的表格

例如,在上图中,Name 是 column1 中的表行项目之一,column2 中的第一行包含 Name 的值。

我该怎么做?

【问题讨论】:

  • 我试过 GridView。但是在设计部分的 GridView 中我们只能添加列而不是行..

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


【解决方案1】:

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


简单粗暴的例子:

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


当然,您必须调整 DataGrid 的外观,这取决于您。

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

【讨论】:

  • 标准 DataGrid 或任何其他标准 WinForm 控件不支持此功能。但是您可以将DataGrid 子类化,在构造函数中将此网格绑定到数据源并创建一个适当的设计器组件,该组件将允许您向该数据源添加元素,但这超出了此问题/答案的范围。
【解决方案2】:
猜你喜欢
  • 2013-12-20
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 2023-01-26
  • 1970-01-01
相关资源
最近更新 更多