2015-10-05 81 views
2

我使用通過存儲過程檢索的數據填充下拉列表(ComboBox)。如何使用單個組合框存儲標識和名稱?

DataTable dtCustomer = da.ExecuteProcedureWithRS("pCustomerList_s", p, parms); //get data 
foreach (DataRow dr in dtCustomer.Rows) //loop through DataTable rows 
{ 
    CustomerNameBox.Items.Add(dr[1]); //add customer name to combobox 
} 

這很簡單。但是,每行的位置0是客戶的ID,我也想跟蹤它,並與CustomerNameBox中的名稱關聯。

一位同事提到我可以再拍下拉菜單,隱藏它,並執行以下操作:從namebox中和它的ID從抓住一個名稱1:

foreach (DataRow dr in dtCustomer.Rows) //loop through DataTable rows 
{ 
    CustomerIDBox.Items.Add(dr[0]); //add customer ID to combobox 
    CustomerNameBox.Items.Add(dr[1]); //add customer name to combobox  
} 

然後我可以匹配名稱標識1 IDBox - 例如var id = CustomerIDBox.Items[16]; var name = CustomerNameBox.Items[16]

這對我來說似乎是一團糟。我知道我可以使用Dictionary<string, int>或類似的存儲鍵值對,但是否有一些方法可以使用單個ComboBox本地存儲ID和名稱?

+1

[SMH]請,不再聽一次你的同事。 – sudheeshix

回答

4

嘗試這樣的:

凡 「鍵」 和 「值」 是列名的數據表

this.comboBox1.DataSource = yourdatatable; 
this.comboBox1.DisplayMember = "Key"; 
this.comboBox1.ValueMember = "Value"; 

或迴路

for(int i=0; i<dtCustomer.Rows.Count();i++) 
{ 
    comboBox1.Items.Add(new ListItem(dtCustomer.Rows[i][0], dtCustomer.Rows[i][1])) 
} 
+0

我感覺好多了,謝謝。單線綁定也是一個很大的改進。 – christophos