![](/img/trans.png)
[英]What is the most elegant way to get a set of items by index from a collection?
[英]Most Elegant Way to Set ComboBox by Value
我通常在做網絡工作,所以請原諒這個話題。
我正在嘗試從下面的代碼中執行“加載組合框”:
using (var con = new SqlConnection(ConStr)) {
try {
var dt = new DataTable();
var cmd = new SqlCommand("usp_SelectContactDropDown", con) {
CommandType = CommandType.StoredProcedure };
var adapter = new SqlDataAdapter {SelectCommand = cmd};
adapter.Fill(dt);
((ComboBox) Controls.Find(ddContact, true)[0]).DataSource = dt;
((ComboBox) Controls.Find(ddContact, true)[0]).DisplayMember = "DisplayText";
((ComboBox) Controls.Find(ddContact, true)[0]).ValueMember = "ID";
((ComboBox) Controls.Find(ddContact, true)[0]).SelectedIndex = -1;
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
finally { /* Handle the error*/ }
其中ID是一個整數。 之后,我想根據值成員設置組合框的選定值。 但是,這似乎比我認為需要的更加棘手。 在ASP中,這非常簡單
ddContact.SelectedValue = o.fk_ContactID.ToString();
您說的是WinForms,因此,除非該組合位於另一個類中,否則應該可以使用
ddContact.DisplayMember = "DisplayText";
ddContact.ValueMember = "ID";
ddContact.DataSource = dt;
ddContact.Value = Convert.ToInt32(dt.Rows[0]["ID"]);
我也假設您從查詢中找到至少一條記錄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.