如何在一个组合框中显示两个不同的列

时间:2013-07-09 01:02:25

标签: c# sql-server-2008

我想在一个特定的组合框中显示两个不同的列。当我运行它时,将显示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";


}

3 个答案:

答案 0 :(得分:1)

我看到你已经在创建一个包含“组合”值的结果列。那是战斗。

但是,您需要为列添加名称(请注意AS FullName别名):

cmd.CommandText = "SELECT CustomerID, firstname + ',' + lastname AS FullName " +
    "FROM Customer";

因此您可以稍后通过名称引用它:

cboName.DisplayMember = "FullName";

答案 1 :(得分:1)

这会奏效。我发现将Dictionary绑定到ComboBox具有更可预测的结果。

我的方法省略了额外的SQL语法,DataSetSqlDataAdapter

相反,我使用SqlDataReader将所需信息放入Dictionary,然后将Dictionary绑定为DataSource的{​​{1}}。< / p>

Combobox

答案 2 :(得分:0)

检查一下:

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

最好的问候