2011-02-12 36 views
0

我想我知道如何從前做,但我想不出它現在不在。我試圖在具有關聯值的組合框中分配一個列表項。原因是因爲我使用數據庫中的名稱列表填充它,但我希望它將主鍵存儲爲值,以便我可以在後續查詢中直接調用它。例如,您從主管人員列表中選擇一個名稱,該主管人員將該主管人員的主鍵存儲在一個變量中,以用於列出所有將該鍵值分配給他們作爲主管的員工的事件。有道理?相當標準。下面是我有一個加載的姓名或名稱只是文本部分:C#:分配文本和值組合框成員

查詢:

static string sql = "select rtrim(elname),rtrim(efname) from employee where pos_id = 2"; 

用於填充列表的代碼:

try 
      { 
       conn.Open(); 
       //determine how many records affected/returned    
       int records = dbAdapter.Fill(results); //fills the datatable with results and returns the number of records 

       if (records > 0) 
       { 
        //do something with the results (stored in the datatable) 
        foreach (DataRow dr in results.Rows) 
        { 
         cboSupervisor.Items.Add(dr[0] + ", " + dr[1]); 

        } 
        cboSupervisor.Sorted = true; 
       } 
      } 
      catch { } 

這將填充下拉與姓氏,名字

回答

3

最好的方法是創建一個包含要顯示的信息和想要保留的信息的類,然後專門設置ToString():

public class ComboItem : object 
    { 
     protected String name; 
     .... 
     .... 
     protected int id; 

     public ComboItem(String name, int id) 
     { 
      this.name= name; 

      this.id = id; 
     } 

     public override string ToString() 
     { 
      return name; 
     } 

    }; 
+0

就像在網上你有一個選擇框,它顯示一件事物,但保存一個值。即時通訊尋找做同樣的事情 – Sinaesthetic 2011-02-12 04:40:58

0

你可以使用一個ComboBoxItem,使用內容屬性來設置名稱,並使用Tag屬性設置值?然後將ComboBoxItem添加到您的ComboBox的Items集合中?