2012-08-22 45 views
0

我想添加一個表格到表格中,包含2列和3行。3行是名稱,年齡和地點。在這個表格中,我希望在運行時更新第二列中相關行的值。 我要添加表這樣如何將表格控件添加到表單中?

​​

對於eg.In上圖中名稱是列1和列2中的第一行的錶行項目的名稱包含的價值之一。

我該怎麼辦?

+0

使用一個DataGrid也許 – sloth

+0

我試圖GridView.But在GridView控件設計的一部分,我們只能添加列不列... –

回答

1

創建某種容器類(即某些類型的集合),其存儲您的鍵值對,並綁定th em在運行時爲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對象,並且您可以輕鬆讀取/更改值。

+0

ok..But我想添加在設計模式中只排不代碼 –

+0

這是不支持通過標準的'DataGrid'或任何其他標準的WinForm控件。但是你可以繼承DataGrid的子類,將構造函數中的這個網格綁定到數據源,並創建一個適當的設計器組件,它允許你向該數據源添加元素,但這不屬於這個問題/答案的範圍。 – sloth

相關問題