从表中绑定两个列的组合框

时间:2015-01-01 11:23:53

标签: c# data-binding combobox

我如何加入这些数据,或者有更好的方法?

数据加入时的示例accountID - accountname

          public void BindData()
          {
                cn.Open();
                string strCmd = "select accountID from MsAccount";
                string strCmd2 = "select accountName from MsAccount";
                SqlCommand cmd = new SqlCommand(strCmd, cn);
                SqlCommand cmd2 = new SqlCommand(strCmd2, cn);
                SqlDataAdapter da = new SqlDataAdapter(strCmd, cn);
                SqlDataAdapter da2 = new SqlDataAdapter(strCmd2, cn);
                DataTable dt = new DataTable();
                DataTable dt2 = new DataTable();
                da.Fill(dt);
                da2.Fill(dt2);
                comboBox1.DataSource = dt;
                comboBox1.ValueMember = "AccountID";
                comboBox1.DataSource = dt2;

                comboBox1.ValueMember =  "accountName";

                comboBox1.DisplayMember = "AccountID"+ "-"+"accountName";<<OUTPUT that i need
                //comboBox1.DisplayMember = "accountName";

                comboBox1.Enabled = true;
                comboBox2.Enabled = true;
                cmd.ExecuteNonQuery();
                cn.Close();
           }

1 个答案:

答案 0 :(得分:0)

您可以使用

   SELECT 
         accountID, 
         (CAST(accountID AS VARCHAR(10))+'-'+accountName) AS accountName 
    FROM 
         MsAccount

而是单独称呼它们。

public void BindData()
          {
                cn.Open();
                string strCmd = "SELECT accountID, (CAST(accountID AS VARCHAR(10))+'-'+accountName) AS accountName FROM MsAccount";
                SqlCommand cmd = new SqlCommand(strCmd, cn);
                SqlDataAdapter da = new SqlDataAdapter(strCmd, cn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                comboBox1.DataSource = dt;
                comboBox1.ValueMember = "accountID";
                comboBox1.DisplayMember =  "accountName";
                comboBox1.Enabled = true;
                cn.Close();
           }