【问题标题】:Setting up comboboxes in a datagridview bound to a collection在绑定到集合的 datagridview 中设置组合框
【发布时间】:2012-08-10 22:44:57
【问题描述】:

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

谢谢, 格雷格

【问题讨论】:

    标签: winforms collections datagridview combobox


    【解决方案1】:

    这是一个简单的数据类:

    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。

    【讨论】:

    • 感谢 LarsTech。我会试试的。
    猜你喜欢
    • 2013-08-10
    • 2011-02-25
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    相关资源
    最近更新 更多