![](/img/trans.png)
[英]How to display two combobox columns in Datagrid from Dto with collections?
[英]How to display two different columns in one combobox
我想在一個特定的組合框中顯示兩個不同的列。 當我運行它時,將顯示Customer ID
。 這是我的代碼。
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname
+ ',' + lastname FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "Customer.firstname, Customer.lastname";
cboName.ValueMember = "Customer.CustomerID";
}
我看到你已經在創建一個包含“組合”值的結果列。 那是戰斗。
但是,您需要為列命名(請注意AS FullName
別名):
cmd.CommandText = "SELECT CustomerID, firstname + ',' + lastname AS FullName " +
"FROM Customer";
所以你以后可以通過名字引用它:
cboName.DisplayMember = "FullName";
這會奏效。 我發現將Dictionary
綁定到ComboBox
具有更可預測的結果。
我的方法省略了額外的SQL
語法, DataSet
和SqlDataAdapter
。
相反,我使用SqlDataReader
將所需信息放入Dictionary
,然后將該Dictionary
綁定為Combobox
的DataSource
。
void GetRecords2()
{
Dictionary <int, string> myDict = new Dictionary<int, string>();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname, lastname FROM Customer";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
myDict.Add(Convert.ToInt32(reader["CustomerID"]),
reader["firstname"].ToString() + " " + reader["lastname"].ToString());
}
if (myDict.Count > 0)
{
cboName.DataSource = new BindingSource(myDict, null);
cboName.DisplayMember = "Value";
cboName.ValueMember = "Key";
}
}
檢查一下:
void GetRecords2()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT CustomerID, firstname
+ ',' + lastname FullName FROM Customer";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Customer");
cboName.DataSource = ds;
cboName.DisplayMember = "FullName";
cboName.ValueMember = "CustomerID";
}
要獲得選定的值:
string customerid = cboName.SelectedValue.toString(); //CustomerID: 1
獲取所選項目
string fullname = cboName.SelectedItem.Text; //FullName : John Hawkins
最好的祝福
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.