【问题标题】:Setting DataPropertyName in DataGridViewComboBoxColumn from BindingSource从 BindingSource 在 DataGridViewComboBoxColumn 中设置 DataPropertyName
【发布时间】:2014-01-31 05:51:09
【问题描述】:

我在为 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 是字符串列表。但它不起作用。应该给它分配什么样的属性?

【问题讨论】:

    标签: c# .net winforms binding


    【解决方案1】:

    您需要为该列指定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];
        }
    }
    

    【讨论】:

    • 很抱歉回复晚了,但我刚刚找到了一些时间考虑一下。好吧,我尝试了你的方法,但我必须遗漏一些东西,因为我的组合框仍然是空的。我注意到,如果我在我的 init 函数中另外添加 2 行代码:var dependenciesColumn = (DataGridViewComboBoxColumn) pluginsDataGridView.Columns["pluginDependencies"]; dependenciesColumn.DataPropertyName = "Dependencies"; 我显然会得到 na 错误(每次我尝试将鼠标悬停在 ComboBox 上,它说 DataGridViewComboBoxCell 值无效),但同时我终于可以看到想要的组合框选项了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多