2012-03-17 87 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