2014-09-19 85 views
0

我正在處理visual studio 2012 c#... 我將值插入combox中...我從數據庫中取出它們...我想知道如何將一個項目添加到組合框中...虐待顯示ü下面的代碼:插入數據源combobox

下面這個函數,以填補containig名稱和ID從表中取數據庫名稱組合框:

List<Lookup> fillCombo(string query, string column) 
    { 
     List<Lookup> lookups = new List<Lookup>(); 
     using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString)) 
     { 
      conn.Open(); 
      SqlCommand cmd = new SqlCommand(query, conn); 
      SqlDataReader reader = cmd.ExecuteReader(); 
      while (reader.Read()) 
      { 
       Lookup lookupobject = new Lookup(); 
       lookupobject.ID = Convert.ToInt32(reader["ID"]); 
       //if (reader["Name"] != DBNull.Value) 
       lookupobject.Name = reader[column].ToString(); 

       lookups.Add(lookupobject); 
      } 


      conn.Close(); 
     } 

     return lookups; 
    } 

然後我調用這個函數如下:

lookups = fillCombo("select id,name from LookupDetails where LOOKUPID = (select id from Lookup where Name = 'users')", "name"); 

     comboBox2.DataSource = lookups; 
     comboBox2.DisplayMember = "name"; 
+0

什麼是不工作?這是wpf/winforms? 'lookups'是否包含任何值? – Sayse 2014-09-19 07:58:26

+0

我不能添加項目..我嘗試使用此命令添加項目:comboBox2.Items.Insert(0,「」); 但它沒有工作cz的數據綁定..所以我想知道如何將數據添加到組合框...是列表包含對象列表有每個對象有用戶名和編號 – mhammadkassem 2014-09-19 08:12:28

+0

你需要插入'lookups' – Sayse 2014-09-19 08:13:29

回答

0

設置DataSource屬性時,ComboxBox Items集合無法修改。

您可以選擇修改List<Lookup>,或者通過遍歷List<Lookup>來添加項目到combox中。

下面是選擇使用foreach循環添加在組合框中的項目,並在0指數comboxbox的插入項:

lookups = fillCombo(@"select id,name from LookupDetails where LOOKUPID = 
        (select id from Lookup where Name = 'users')", "name"); 

foreach(var obj in lookups) 
    comboBox2.Items.Add(obj); 

comboBox2.DisplayMember = "Name"; 
comboBox2.Items.Insert(0, ""); 

注意:在問題中提及的代碼,SqlDataReader從來沒有關閉,我已經修改了它通過包括using聲明。你不必關閉SqlDataReaderSqlConnection當你using塊寫這些:

List<Lookup> fillCombo(string query, string column) 
{ 
    List<Lookup> lookups = new List<Lookup>(); 
    string sConstring = ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString; 
    using (SqlConnection conn = new SqlConnection(sConstring)) 
    using(SqlCommand cmd = new SqlCommand(query, conn)) 
    { 
     conn.Open(); 
     using(SqlDataReader reader = cmd.ExecuteReader()) 
     { 
      while (reader.Read()) 
      { 
       Lookup lookupobject = new Lookup(); 
       lookupobject.ID = Convert.ToInt32(reader["ID"]); 
       //if (reader["Name"] != DBNull.Value) 
       lookupobject.Name = reader[column].ToString(); 
       lookups.Add(lookupobject); 
      } 
     } 
    }   

    return lookups; 
}