【问题标题】:How to bind datagridview's data source property to combobox?如何将 datagridview 数据源属性绑定到组合框?
【发布时间】:2017-12-07 15:45:36
【问题描述】:

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

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

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

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

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

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

dataGridView.AutoGenerateColumns = false;
DataGridViewComboBoxColumn dgvc = new DataGridViewComboBoxColumn();
dgvc.HeaderText = "Products";
dgvc.DataSource = dbc.GetAllProducts();
dgvc.DisplayMember = "Name";
dgvc.ValueMember = "ID";
dataGridView.Columns.Add(dgvc);
dataGridView.Columns[0].DataPropertyName = "productID";

和 dbc.GetAllProducts() 返回列表和:

Class Products
{
 int ID;
 string Name; 
}

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

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

【问题讨论】:

  • 您是否查看了调试器并检查了所有内容的值?
  • @MethodMan 在我的问题开头,dataGridView.DataSource = s;

标签: c# winforms datagridview combobox


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多