2014-01-12 55 views
0

我在爲DataGridViewComboBoxColumn的DataPropertyName設置正確的數據屬性時遇到問題。我有一個BindingSource,並將其DataSource設置爲自定義對象的BindingList。這些對象有我想指定爲在DataGridView列的屬性(pluginsDataGrid):從BindingSource在DataGridViewComboBoxColumn中設置DataPropertyName

var source = new BindingSource {DataSource = _plugins}; 
pluginsDataGrid.AutoGenerateColumns = false; 
pluginsDataGrid.DataSource = source; 

一切都很好,當我有一個簡單的字符串作爲一個屬性 - 它是名稱:

using (var nameCol = new DataGridViewTextBoxColumn()) 
{ 
     nameCol.DataPropertyName = "Name"; 
     nameCol.Name = "Name"; 
     pluginsDataGrid.Columns.Add(nameCol); 
} 

但我不知道如何設置DataGridViewComboBoxColumn選項。我試試這個方法:

using (var depCol = new DataGridViewComboBoxColumn()) 
{ 
    depCol.DataPropertyName = "Dependencies"; 
    depCol.Name = "Dependencies"; 
    pluginsDataGrid.Columns.Add(depCol); 
} 

其中Dependencies是一個字符串列表。但它不起作用。應該分配哪種財產?

回答

2

你需要指定數據源的列,例如:

 comboboxColumn.DataSource = collection; 
     comboboxColumn.ValueMember = ColumnName; 
     comboboxColumn.DisplayMember = ValueMember; 

在你的情況下使用DataBindingComplete事件psecify集合:

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
{ 
    for (int i = 0; i < dataGridView1.Rows.Count; i++) 
    { 
     DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells["Dependencies"]; 
     [Plugin_Type] entry = dataGridView1.Rows[i].DataBoundItem as [Plugin_Type]; 

     comboCell.DataSource = entry.[YOUR_PROPERTY]; 
    } 
} 
+0

對不起,後期的答覆,不過我已經發現了一些有時間想一想。好吧,我嘗試了你的方法,但我必須錯過一些東西,因爲我的組合框仍然是空的。我注意到,如果我在我的init函數中添加2行代碼: 'var dependenciesColumn =(DataGridViewComboBoxColumn)pluginsDataGridView.Columns [「pluginDependencies」]; dependenciesColumn.DataPropertyName =「Dependencies」;' 顯然我會得到na錯誤(每當我嘗試懸停在ComboBox上,它說DataGridViewComboBoxCell值無效),但在同一時間,我終於可以看到想要的組合框選項 – krajol

+0

你知道爲什麼它是這樣的,我怎麼才能使它工作? – krajol

相關問題