填充ComboBox

时间:2012-07-17 09:13:49

标签: c#

我的方案是从数据库中填充组合框,显示客户名称,并使用标识增量保存id的值。

运行此代码时,收到错误Procedure or function 'spSelectCustomerById' expects parameter '@id', which was not supplied

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();

//SelectCustomerById(int x);
comboBoxEx1.Items.Clear();

SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
//comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
//comm.CommandText = "spSelectCustomerByID";
comm.Parameters.Add(new SqlParameter("cust_id", SqlDbType.Int));
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();

SqlDataAdapter sdap = new SqlDataAdapter(comm);
DataSet dset = new DataSet();
sdap.Fill(dset, "cust_registrations");

if (dset.Tables["cust_registrations"].Rows.Count > 0)
{
    comboBoxEx1.Items.Add("cust_registrations").ToString();
}
comboBoxEx1.DataSource = dset;
comboBoxEx1.DisplayMember = "cust_name";

如何从数据库中填充组合框?

2 个答案:

答案 0 :(得分:0)

对于网络组合框我们comboBoxEx1.DataValueField = "cust_id";

对于WPF,您使用comboBoxEx1.SelectedValuePath = "cust_id";

胜利表单中的

使用comboBox1.ValueMember = "cust_id";

答案 1 :(得分:0)

 conn.Open();

        //SelectCustomerById(int x);
        comboBoxEx1.Items.Clear();
        SqlCommand comm = new SqlCommand("spSelectCustomerByID", conn);
        //comm.Parameters.Add(new SqlParameter("cust_name", cust_name));
        //comm.CommandText = "spSelectCustomerByID";
        comm.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));
        comm.CommandType = CommandType.StoredProcedure;
        comm.ExecuteNonQuery();
        SqlDataAdapter sdap = new SqlDataAdapter(comm);
        DataSet dset = new DataSet();
        sdap.Fill(dset, "cust_registrations");        
        comboBoxEx1.DataSource = dset;
        comboBoxEx1.DisplayMember = "cust_name";

//添加以下行 //您无需在组合框中添加项目。

        comboBoxEx1.ValueMember = "cust_id";
        comboBoxEx1.DataBind();