2014-09-30 82 views
0

我是VS C#和Winforms中技能水平较低的SQL DBA。我一直在为DataGridView列添加一个组合框而苦苦挣扎了好几天,并且已经放弃了。我有一个datatable dt1和datagridview dg1。 dg1.Datasource = dt1; dt1是数据集ds1的成员。我正在提供数组中的组合项。如何将ComboBox添加到绑定到数据表的WINFORM datagridview

我试过自动生成真假。

如果自动生成=真我与1个组合框同名的两列,它是在错误的列位置,我从DT1

得到正确的数据如果是假,我编程的方式定义列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; 

    } 

回答

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>; 
相关问题