【问题标题】:Datagridview allowing user to add or delete rows with a combo box columnDatagridview 允许用户使用组合框列添加或删除行
【发布时间】:2019-01-20 10:36:33
【问题描述】:

我需要设置一个基于两个类的DataGridView,如下

public class Selection 
{
    public string Display { get; protected set; }
    public int Value { get; protected set; }

    public Selection( string d, int v)
    {
        Display = d; Value = v;
    }
}

public class TestData
{
    public Selection Selection { get; protected set; }
    public int Quantity { get; protected set; }

    public TestData( Selection sel, int q)
    {
        Selection = sel;
        Quantity = q;
    }
}

TestData 对象是行。用户必须从由 List 或类似内容填充的 ComboBox 列中选择一个选项。 但是 TestData 集合必须是 BindingList 才能允许添加或删除行,因此,它是 datagrid DataSource。 到目前为止,我正在尝试使用以下代码设置网格

    List<Selection> getSelectionList()
    {
        List<Selection> result = new List<Selection>();

        result.Add(new Selection("Zero", 0));
        result.Add(new Selection("One", 10));
        result.Add(new Selection("Two", 20));
        result.Add(new Selection("Three", 30));
        result.Add(new Selection("Four", 40));
        result.Add(new Selection("Five", 50));
        result.Add(new Selection("Six", 60));

        return result;
    }

    List<TestData> getTestDataList(List<Selection> reference)
    {
        List<TestData> result = new List<TestData>();
        result.Add(new TestData(reference[1], 10));

        return result;
    }

................
        DataGridViewComboBoxColumn combo = (DataGridViewComboBoxColumn)dataGridView1.Columns[0];
        List<Selection> list = getSelectionList();
        combo.DataSource = list;
        combo.DisplayMember = "Display";
        combo.ValueMember = "Value";

        BindingList<TestData> source = new BindingList<TestData>(getTestDataList(list)) { AllowEdit = true, AllowNew = true, AllowRemove = true };

        dataGridView1.DataSource = source;
................

但结果很烦人: a) 网格显示两行(即使我在 TestData 列表中只设置了一个元素) b) 组合单元格中没有数据。

我该如何解决这个问题?

TIA

【问题讨论】:

    标签: c# winforms datagridview binding


    【解决方案1】:

    你只需要添加两行:

    string key = ((KeyValuePair<string, string>)combo.SelectedItem).Key;
    string value = ((KeyValuePair<string, string>)combo.SelectedItem).Value;
    

    【讨论】:

    • 我需要在哪里或向哪个对象添加这些行?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多