在绑定到集合的datagridview中设置组合框

时间:2012-08-14 15:29:01

标签: winforms collections datagridview combobox

我有一个问题,希望有人可以帮助我。我的问题涉及Visual Studio 2008中的winforms和datagridview。我想将datagridview绑定到业务对象的集合而不是数据集。我想在datagridview中有组合框,它从业务对象中的一个属性获取其值。这可能吗?有人可以提供示例代码或提供描述如何执行此操作的网页。任何帮助将不胜感激。

谢谢, 格雷格

1 个答案:

答案 0 :(得分:0)

这是一个简单的数据类:

Public Class MyData

  Private _ID As Integer
  Private _ItemValue As String

  Public Sub New(ByVal id As Integer, ByVal itemValue As String)
    _ID = id
    _ItemValue = itemValue
  End Sub

  ReadOnly Property ID() As Integer
    Get
      Return _ID
    End Get
  End Property

  Public Property ItemValue() As String
    Get
      Return _ItemValue
    End Get
    Set(ByVal value As String)
      _ItemValue = value
    End Set
  End Property

End Class

创建一个表单并在其上放置一个DataGridView控件,添加以下代码:

Private myList As New List(Of String)
Private myItems As New List(Of MyData)

Protected Overrides Sub OnLoad(ByVal e As EventArgs)
  MyBase.OnLoad(e)

  myList.Add("First Item")
  myList.Add("Last Item")

  myItems.Add(New MyData(1, "Last Item"))
  myItems.Add(New MyData(2, "First Item"))

  DataGridView1.AutoGenerateColumns = False
  DataGridView1.Columns.Add(New DataGridViewTextBoxColumn() With _
                           {.HeaderText = "ID", _
                            .DataPropertyName = "ID"})
  DataGridView1.Columns.Add(New DataGridViewComboBoxColumn() With _
                           {.HeaderText = "ItemValue", _
                            .DataSource = myList, _
                            .DataPropertyName = "ItemValue"})

  DataGridView1.DataSource = myItems
End Sub

由于您需要在网格中使用组合框,因此必须将AutoGenerateColumns设置为false并自行创建,通过DataPropertyName属性将每列映射到类中的属性。对于组合框,您可以为下拉项列表设置自己的DataSource