2012-03-17 77 views
1

非常好,下午所有, 我现在的问题是,我无法获得选定的值作为组合框,我试图设置文本和值的每个项目数据网格中每个单元格的组合框。 我的代码:获取DataGridViewComboBoxCell的SelectedItem VB.NET

CLASS MyListItem:

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 

窗体的Load:

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.DataGridViewCom的成员boBoxCell”

如果任何人有任何想法如何的值和文本设置与组合框每个单元的每个项目,我会非常感激感谢

回答

1

您需要使用Value属性根据MSDN documentation

Unlike the ComboBox control, the DataGridViewComboBoxCell does not have SelectedIndex and SelectedValue properties. Instead, selecting a value from a drop-down list sets the cell Value property.

要加载的DataGridViewComboBoxCell你需要设置DataSource

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

下面是从MSDN上的数据源的一些额外的指导:

Typically this property will be set for an entire column of cells through the DataGridViewComboBoxColumn.DataSource property.

If possible, set DataSource to a source containing only the possible selections, like a column of selections. Then the DisplayMember property doesn't need to be set. But if the source is more complicated, set DisplayMember to the name of the property or column from which to retrieve possible selections.

If DataSource is set to a string array, then ValueMember and DisplayMember do not need to be set because each string in the array will be used for both value and display.

所以你的情况,你需要做类似下面的东西:

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的变量。

+0

是的,但你可以给我一个例子,我怎么可以指定并得到值蚂蚁组合框的每一个项目?谢谢 – 2012-03-17 23:58:27

+0

我已经更新了更多的信息和解决问题的建议方法的答案。 – 2012-03-18 00:43:19

+0

以及我看到,正确赋值,但我有另一个问题,但在结束问题之前,因为我可以显示ITEM的价值改变comobobox ?,再次感谢和抱歉造成的不便 – 2012-03-18 02:13:22