2010-05-02 130 views
4

這裏是我的代碼:的DataGridViewComboBoxCell設定值,值無效

 private class Person 
     { 
      private string myName; 
      private int myValue; 

      public Person(string name, int value) 
      { 
       myName = name; 
       myValue = value; 
      } 
      public override string ToString() 
      { 
       return myName; 
      } 

      public string Name 
      { 
       get { return myName; } 
       set { myName = value; } 
      } 

      public int Value 
      { 
       get { return myValue; } 
       set { myValue = value; } 
      } 
     } 

我用它來填充的DataGridViewComboBoxCell這樣的:

myDataGridViewComboBoxCell.ValueMember = "Value"; 
myDataGridViewComboBoxCell.DisplayMember = "Name"; 
myDataGridViewComboBoxCell.Items.Add(new Person("blabla", someNumber)); 

所有我想現在要做的就是選擇一個人:

myDataGridViewComboBoxCell.Value = someNumber; 

但不斷收到「值無效」 - 錯誤。任何想法爲什麼? 當我選擇在我的計劃,我可以看到正確的價值(someNumber),因此顯示和ValueMember正確設置項...

回答

9

而不是增加DataGridViewComboBoxColumn.Items,你需要設置DataGridViewComboBoxColumn.DataSource到人的名單,並設置DataGridViewComboBoxColumn.ValueType = typeof(Person)

應該這樣做。雖然自從你問這個問題已經兩個月了,你的問題可能已經失去了它的緊迫感。

+0

我無法在DataGridView上看到ValueType屬性。你的意思是'DataGridViewComboBoxColumn'? – Brij 2013-07-06 07:12:57

+1

是的,它在'DataGridViewComboBoxColumn'上。 – 2014-03-14 18:03:05

+0

@SimonDugré,感謝您的編輯。晚了。累。你知道...... – Spike 2014-10-07 01:18:30

2

我也有這個問題。我暫時以相當骯髒的方式解決了這個問題。

一個的DataGridViewComboBoxCell的Value屬性必須包含在項目屬性的一個值(或綁定數據源)

的問題是,因爲我不知道它的原因,電池的項目列表中(或它的數據源時我試圖不手動輸入項目)只要執行進入該單元的DataGridView.CellFormatting事件處理程序就被清除。

我骯髒的修復方法是處理DataGridView.DataError事件,並填充(再次)DataGridViewComboBoxCell.Items在那一點。

Private Sub myDataGridView_DataError(ByVal sender As System.Object, _ 
       ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) _ 
       Handles dgvServicesToTransfer.DataError 

     'Dirty Fix 
     If e.ColumnIndex = myComboBoxColumn.Index Then 
      Dim row As DataGridViewRow = dgvServicesToTransfer.Rows(e.RowIndex) 
      ' Fill in your DataGridViewComboBoxCell's Items here: 
      ' ... 
      ' ... 
      If allWentWell Then 
       ' Cancel the exception 
       e.ThrowException = False 
      End If 
     End If 

    End Sub 
End Class 

PS:抱歉VB.Net的答案,如果你有問題「翻譯」它只是問。

+0

這也讓我感覺良好。我將顯示和值成員與valuetype一起設置,但仍存在問題。在當前的下拉列表中找不到價值幫助我找到根本原因。 – BrandonG 2016-06-18 16:47:26

-5

嘗試使用枚舉爲你的ComboBox

myDataGridViewComboBoxCell.Items.Add (person.andy.tostring(),number); 

現在當你要重新設置淡水河谷使用枚舉你的人的名字

enum person 
{ 
John, 
Andy, 
Sepehr 
}; 

使用此枚舉來添加名字。泰國人會解決你的問題。

myDataGridViewComboBoxCell.Value = person.Andy.ToString() ; 

記住使用 - >ToString()! 爲我工作! :)

+2

Enuming names?這使得你的系統非常不靈活,當一個新人加入時會發生什麼,你必須重新編譯代碼。 – Skuld 2012-02-03 16:23:26

+2

使用人名的枚舉可能是我見過的StackOverflow中最糟糕的建議。 – Rophuine 2013-10-11 02:18:33

0

我有類似的問題。聽起來很奇怪,我通過只向DataGridViewComboBoxCell.Items添加字符串來解決它。添加對象(使用ToString()很好實現等)導致這些「數據錯誤」的問題,但添加字符串工作正常。