簡體   English   中英

如何在一個組合框中顯示兩個不同的列

[英]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語法, DataSetSqlDataAdapter

相反,我使用SqlDataReader將所需信息放入Dictionary ,然后將該Dictionary綁定為ComboboxDataSource

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM