2009-02-05 66 views
1

我不知道我的頭腦是不是今天工作,或者如果這實際上比我認爲應該更難。如何在綁定的DataGridViewComboBoxCell中獲取對基礎對象的引用?

我有一個DataGridView DataGridViewComboBoxColumn綁定到一個通用的IList的CustomObjects。以下是我如何設置列的粗略代碼示例。

DataGridViewComboBoxColumn location = new DataGridViewComboBoxColumn() 
{ 
    Name = "Location", 
    DataSource = new BindingSource(GetMyLocations(), null), 
    DisplayMember = "Name", 
    ValueMember = "ID" 
}; 

然後,當我想返回一個單元格的值:

string id = (string)row.Cells["Location"].Value; 

但我不希望將ID屬性的引用,我想實際的位置對象的引用!我試過沒有指定一個ValueMember,但似乎只是使用DisplayMember。

我可以迭代列DataSource中的所有Location對象並檢查匹配的ID屬性,但是,它似乎像ComboBoxCell應該能夠直接返回。

此外,我不能在這種情況下使用字典。

任何想法,以實現它的最佳方式?

回答

1

您可以使用「Name」的KeyValuePair s的IList和您的自定義對象。這個想法是你需要ValueMember指向你的對象的引用。我記得有一段時間與ComboBox es有類似的問題。

類似下面應該做的伎倆(把我的頭頂部,未經測試):

IList<KeyValuePair<String,MyObject>> comboData = 
    new IList<KeyValuePair<String,MyObject>>(); 

foreach(var o in GetMyLocations()) 
    comboData.Add(new KeyValuePair<String,MyObject>(o.Name, o)); 

DataGridViewComboBoxColumn location = new DataGridViewComboBoxColumn() 
{ 
    Name = "Location", 
    DataSource = comboData, 
    DisplayMember = "Key", 
    ValueMember = "Value" 
}; 

您可能要更改GetMyLocations()返回KeyValuePair列表,而不是,所以你不填充兩個名單沒有理由。

0
public class Thing 
{ 
    public string id{ get ; set ; } 
    public string Name { get ; set ; } 

    //self ref 
    public Thing This 
    { 
     get { return this; } 
    } 
} 



form_load(){ 
     comboboxcell.ValueMember = "This"; // self ref 
     comboboxcell.DisplayMember = "Name"; 
} 


datagridview1.CellValueChanged += (s, e) => { 
    var cb = (DataGridViewComboBoxCell)dgv_titles.Rows[e.RowIndex].Cells[e.ColumnIndex]; 
    var selectedObject = (Thing)cb.Value ; 
} 

這就是easieset和最乾淨的方式遇到。

http://mikehadlow.blogspot.com/2006/09/problems-with-datagridviewcomboboxcolu.html

相關問題