2012-04-04 17 views
0

我想從我的數據表中獲取一列以在我的網格視圖中顯示爲組合框。還需要有能力用一個小集合填充組合來選擇。它不會顯示值時,我把它從Gui綁定,所以我試圖編程,但似乎無法找到正確的代碼。從DataTable到GridView的值作爲組合框

connection2 = new MySqlConnection(ConnectionString2); 


     try 
     { 
      string proid = txtbxProjId.Text; 

      //prepare query to get all records from items table 
      string query2 = "select sl.sample_id As sample_id, sl.sample_number As Sample_Number, sl.sample_date As Sample_Date, sl.sample_time As Sample_Time, sl.sample_comments As Sample_Comments FROM spt_sample_login sl Where project_id = '"+proid+"'"; 



      //prepare adapter to run query 
      adapter2 = new MySqlDataAdapter(query2, connection2); 
      adapter3 = new MySqlDataAdapter(query2, connection2); 

      //create a DataTable to hold the query results 
      DataTable dTable2 = new DataTable(); 
      DataSet DS2 = new DataSet(); 

      //fill the DataTable 


      //get query results in dataset 
      adapter2.Fill(dTable2); 
      adapter3.Fill(DS2); 



      //return datatable with all records 
      //BindingSource to sync DataTable and DataGridView 


       //set the BindingSource DataSource 
      GridView1.DataSource = dTable2; 


      this.GridView1.Columns["sample_id"].Visible = false; 

      this.GridView1.Columns["Sample_Type"].DisplayIndex = 4; 
      this.GridView1.Columns["Sample_Type"].Visible = true; 










      //set the DataGridView DataSource 












     } 
     catch (MySqlException ex) 
     { 


     } 
    } 

這工作,但顯示了Sample_Type,那是我希望它是用F,P Q,B中選擇一個組合文本框。

謝謝 布倫特

回答

0

你必須把你的組合框的ItemTemplate中,你有RowDataBound事件期間填充它。

從我目前的項目快速爲例:

DropDownList ddlRole = (DropDownList)e.Row.FindControl("ddlRole"); 

ddlRole.DataSource = GetTruckersRoles(); 

string[] rolesList = Roles.GetRolesForUser((string)gvTruckers.DataKeys[e.Row.RowIndex][0]); 
if (rolesList.Length > 0) 
{ 
    //If user is not in any roles, dont' do this 
    ddlRole.SelectedValue = rolesList[0]; 
} 

ddlRole.DataBind(); 

只需將代碼適應你的情況

+0

謝謝馬丁,但我想我可能是在什麼我能理解,因爲我真的不知道怎麼說作品。基本上我只想從我的數據表中取出樣本類型的行,並將其顯示爲組合框而不是文本框,然後每個添加的新行將是一個組合框,其默認值可以更改爲列表中的一個 – bmorrison1982 2012-04-04 18:44:31

+0

好的。你必須明白你不能像你那樣填充你的ComboBox。因爲你的gridview的行還不存在!你首先需要填寫你的gridview,然後調用你的GridView.DataBind()。 – Bestter 2012-04-05 15:54:30

+0

之後,在你的RowDataBound事件中,你會像我向你展示的那樣填充你的組合框。以下是一個完整的示例:[http://msdn.microsoft.com/en-us/library/aa479353.aspx](http://msdn.microsoft.com/en-us/library/aa479353.aspx) – Bestter 2012-04-05 17:08:40