首页 > 解决方案 > 如何将每行具有不同组合框项的 DataTable 绑定到 DataGridView?

问题描述

我创建了一个这样的通用数据表,很好:

    BindingSource bindingSource1 = new BindingSource();
    bindingSource1.DataSource = CreateDataTable();
    dataGridView1.DataSource = bindingSource1;

    private DataTable CreateDataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("String1"));
        dt.Columns.Add(new DataColumn("String2"));
        DataRow dr = dt.NewRow(); dr["String1"] = "a"; dr["String2"] = "aa"; dt.Rows.Add(dr);
                dr = dt.NewRow(); dr["String1"] = "b"; dr["String2"] = "bb"; dt.Rows.Add(dr);
        //...
        return dt;
    }

但是我需要一个 comboBoxColumn,它在 datatablegrid 中的每一行都有不同的数据源,所以我参考了一些解决方案,尝试将 Columns 和 DataSource 设置为 datagridview :

    dataGridView1.AutoGenerateColumns = false;
    dataGridView1.Columns.Add("String1", "String1");
    dataGridView1.Columns.Add("String2", "String2");
    DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
    comboCol.HeaderText = comboCol.DataPropertyName = comboCol.Name= "combo1";// fixed by ConnorTJ
    dataGridView1.Columns.Add(comboCol);
    
    bindingSource1.DataSource = CreateDataTable();
    dataGridView1.DataSource = bindingSource1;
    
    Dictionary<int, List<string> > comboDic = new Dictionary<int, List<string> >() {
    { 0, new List<string>() { "1", "11", "111" } },
    { 1, new List<string>() { "2", "22", "222" } } };
    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {
        DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells["combo1"];
        comboCell.DataSource = comboDic[i];
        //comboCell.Value = "n";//set the value out of items will throw error
    }

现在字符串列是空的,那么究竟应该如何实现呢?

标签: c#winformsdatatabledatagridviewdatagridcomboboxcolumn

解决方案


你还没有设置实际的 ColumnsName属性,你已经设置了DataPropertyName属性

设置comboCol.Name属性后,执行以下操作时:

var comboCol = new DataGridViewComboBoxColumn
            {
                HeaderText = "combo1",
                DataPropertyName = "combo1",
                Name = "combo1"
            };

然后你可以这样做:

var comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[comboCol.Name];
comboCell.DataSource = comboDic[i];
comboCell.Value = "n";

补充说明:您也可以使用该comboCol.Index属性,这将为您提供列索引。


推荐阅读