从BindingSource在DataGridViewComboBoxColumn中设置DataPropertyName

时间:2014-01-12 13:23:15

标签: c# .net winforms binding

我在为DataGridViewComboBoxColumn的DataPropertyName设置正确的数据属性时遇到问题。我有一个BindingSource,我将其DataSource设置为自定义对象的BindingList。这些对象具有我想在DataGridView(pluginsDataGrid)中指定为列的属性:

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是一个字符串列表。但它没有用。应该分配什么样的财产?

1 个答案:

答案 0 :(得分:2)

您需要为列指定DataSource,例如:

        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];
    }
}