2014-09-30 85 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>; 
相關問題