如何将datagridview的数据源属性绑定到组合框?

时间:2017-12-07 15:45:36

标签: c# winforms datagridview combobox

我试图将对象列表绑定为数据网格的数据源,列的组合应该是一个组合框,其中组合框的选定值应该是我对象中相关字段中的值。

这就是我设置gridview的数据源的方法:

permutecols!

dbc.GetResults(id)将返回List和myClass,它是

permutecols!(df, [:b, :a])

然后我像这样初始化数据网格视图:

var s = new BindingSource();
s.DataSource = dbc.GetResults();
dataGridView.DataSource = s; 

和dbc.GetAllProducts()返回list并:

Class myClass
{
 int productID{ set; get; }
 int price{ set; get; }
}

在这里,我希望数据网格从myClass获取productID并将其传递给每一行的组合框,然后组合框获取productID与产品列中的ID匹配,然后显示它的Name属性。

当我运行它时,我得到DataGridViewComboBoxCell值无效的错误。

1 个答案:

答案 0 :(得分:2)

您应该使用字典将属性绑定到组合:

private Dictionary<int, string> cbProductVals= new Dictionary<int, string>();

使用产品对象填充字典并将其绑定在网格列上。

在您的数据网格AutoGeneratingColumn事件中:

if (e.PropertyName == "productID")
{
    DataGridComboBoxColumn cb = new DataGridComboBoxColumn();
    e.Column = cb;
    cb.ItemsSource = cbProductVals;
    cb.DisplayMemberPath = "Value";
    cb.SelectedValuePath = "Key";
    cb.SelectedValueBinding = new Binding("productID");
    e.Column.Header = "product price";
}