从数据库获取数据根据名称填入组合框?

时间:2012-11-27 09:39:53

标签: c# database

根据名称从数据库填充到组合框的数据...

SqlConnection con = new SqlConnection(@"Data Source=CENTAUR09-PC\SQLEXPRESS;Initial Catalog=Sample;Integrated Security=true");
SqlCommand cmd = new SqlCommand("Select cust_name from customer", con);
con.Open();
comboBox1.DataSource = cmd;
comboBox1.DisplayMember = cmd.ToString();
con.Close();

......数据源和显示成员是什么?

1 个答案:

答案 0 :(得分:3)

这样的事情:

DataTable dt = new DataTable();

    using(SqlConnection con = new SqlConnection(@"Data Source=CENTAUR09-PC\SQLEXPRESS;Initial Catalog=Sample;Integrated Security=true"))
    {
       SqlCommand cmd = new SqlCommand("Select id, cust_name from customer", con); 

       SqlDataAdapter adapter = new SqlDataAdapter(cmd);
       adapter.Fill(dt);

       comboBox1.DataSource = dt.DefaultView; 
       comboBox1.DisplayMember = "cust_name"; 
       comboBox1.ValueMember = "id"; 
    }

修改

最好选择客户PK并将其路径设置为VlaueMember