2

大家下午好,我现在遇到的问题是我无法将值选为组合框,我正在尝试为数据网格中每个单元格的组合框中的每个项目设置文本和值。我的代码:

类我的列表项:

Public Class MyListItem
    Private mText As String
    Private mValue As String

    Public Sub New(ByVal pText As String, ByVal pValue As String)
        mText = pText
        mValue = pValue
    End Sub

    Public ReadOnly Property Text() As String
        Get
            Return mText
        End Get
    End Property

    Public ReadOnly Property Value() As String
        Get
            Return mValue
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return mText
    End Function
End Class

表单加载:

DataGridView1.Rows.Add()
Dim dgvcbc As DataGridViewComboBoxCell = DirectCast(DataGridView1.Rows(0).Cells(0), DataGridViewComboBoxCell)
dgvcbc.Items.Add(New MyListItem("Text to be displayed", "value of the item"))

尝试显示选定的值:

Dim oItem As MyListItem = CType(**dgvcbc.SelectedItem**, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)

错误: “SelectedItem”不是“System.Windows.Forms.DataGridViewComboBoxCell”的成员

如果有人知道如何使用组合框为每个单元格的每个项目设置值和文本,我将不胜感激谢谢

4

1 回答 1

1

您需要Value根据MSDN 文档使用该属性:

与 ComboBox 控件不同,DataGridViewComboBoxCell 没有 SelectedIndex 和 SelectedValue 属性。相反,从下拉列表中选择一个值会设置单元格值属性。

要加载 DataGridViewComboBoxCell 您需要设置DataSource

根据数据源中的数据类型,您可能还需要设置 DisplayMember 以选择要在控件的显示部分显示的属性或列名,并设置 ValueMember 以选择用于设置选择项目时控件的值属性。

以下是 MSDN 关于数据源的一些额外指导:

通常,将通过 DataGridViewComboBoxColumn.DataSource 属性为整列单元格设置此属性。

如果可能,将 DataSource 设置为仅包含可能选择的源,例如一列选择。然后不需要设置 DisplayMember 属性。但如果源更复杂,请将 DisplayMember 设置为从中检索可能选择的属性或列的名称。

如果 DataSource 设置为字符串数组,则不需要设置 ValueMember 和 DisplayMember,因为数组中的每个字符串都将用于值和显示。

因此,在您的情况下,您将需要执行类似于以下的操作:

Dim cListItems As New System.Collections.Generic.List(Of MyListItem)

cListItems.Add(New MyListItem("Text to be displayed", "value of the item"))

Dim dgvcbc As DataGridViewComboBoxCell = DirectCast(DataGridView1.Rows(0).Cells(0), DataGridViewComboBoxCell)
dgvcbc.DataSource = cListItems
dgvcbc.DisplayMember = "Text"
dgvcbc.ValueMember = "Value"

最后,如果所有单元格的值都相同,那么您可能希望在创建列时将数据源分配给该列。上述所有代码都将保持不变,除了您将dgvcbc引用替换为包含datagridviewcomboboxcolumn.

于 2012-03-17T23:21:25.817 回答