如何将ComboBox添加到绑定到datatable的WINFORM datagridview

时间:2014-09-30 14:32:09

标签: c# winforms datagridview combobox

我是VS C#和Winforms中技能水平较低的SQL DBA。我一直在努力将一个组合框添加到DataGridView列几天并放弃了。我有一个数据表dt1和datagridview dg1。 dg1.Datasource = dt1; dt1是数据集ds1的成员。我从数组中提供组合项目。

我尝试过自动生成真假。

如果autogeneration = true,我会得到两个同名的列和一个组合框,它位于错误的列位置,我从dt1得到正确的数据

如果为false,我以编程方式为dg1定义列,则不会从dt1获取任何数据。

我的代码应该是什么样的以及我缺少哪些可能的绑定或属性,以便在第4列位置添加'GRADE'的组合框,dg1从dt1填充,从阵列填充组合。

在阅读了数十篇博客并尝试了好几天之后,感到非常沮丧。请帮忙。

    private DataGridViewComboBoxColumn CreateComboBox()
    {
        DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
        {
            combo.Name = "comboColumn";
            combo.HeaderText = "Grade";
            ArrayList drl = new ArrayList();
            drl.Add("GS1");
            drl.Add("GS2");
            drl.Add("WG1");
            drl.Add("WG2");
            combo.Items.AddRange(drl.ToArray());
            combo.DataSource = drl;
            //combo.ValueMember = "EmployeeID";
            //combo.DisplayMember = "Grade";
            //combo.DataPropertyName = "Grade";
        }
        return combo;
    }

    public Employee()
    {
        InitializeComponent();
        WindowState = FormWindowState.Maximized;
        Ds1 = new DataSet("ds1");

        Dt1 = new DataTable("dt1");

        ds1.Tables.Add(dt1);

        dt1.Columns.Add("EmployeeID");
        dt1.Columns.Add("FirstName");
        dt1.Columns.Add("LastName");
        dt1.Columns.Add("Grade");
        dt1.Columns.Add("DOB");

        //initialize datagridview
        Dg1.AutoGenerateColumns = true;

        //dg1.Columns.Add("column4", " EmployeeID ");
        // dg1.Columns.Add("column4", " FirstName ");
        // dg1.Columns.Add("column4", " LastName ");
     Dg1.Columns.Add(CreateComboBox());
        // dg1.Columns.Add("column5", " DOB ");

        Dg1.DataSource = dt1;

    }

1 个答案:

答案 0 :(得分:0)

已解决:经过几天的搜索和尝试,我尝试了一个我认为不会起作用的解决方案,因为它提到了一个未绑定的列,并且似乎需要SQL或其他连接使其成为绑定列。事实证明,没有必要绑定列。这是你做的。

1.Open your Form designer an place Focus on your DataGridView and select properties.

2.Scroll down to the Columns collection (mine was at the bottom under Misc.) and expand the collection.
3.Add Column name and if binding to DataTable set the DataPropertyName to the dt column.  In my case I set both the same. 
Also there is a drop down to choose the ColumnType
4.Add your ComboBox column.  This has a few more settings.  You should look through all of them but I was interested in Items &
HeaderText only.  I set HeaderText the same as ColumnName &
DataPropertyName.  I then opened the Items and added my list.  
There is also a DataSource. I presume that is for populating your
ComboBox from a database, service, or sharepoint but I'm not doing
that.
5.That's it.

在.cs代码文件中,您需要插入两行代码。我把我放在表格的顶部,在那里我声明了我需要所有方法的数据表。

<yourdatagridview>.AutoGenerateColumns = false;
<yourdatagridview>.DataSource = <yourdatatable>;