如何在组合框中选择不同的项目时动态更改组合框

时间:2012-11-05 11:50:14

标签: c#

  string sSql = "Select id from Master.Materialname where Material = '" +                
                    comboBox3.SelectedValue + "'"; 
  SqlCommand cmd = new SqlCommand(sSql,objConn1); 
  int mid = Convert.ToInt32(cmd.ExecuteScalar()); 
  string reffSql = "Select Process from Master.ProductionProcess where id = '" + mid + "'"; 
  SqlCommand rcmd = new SqlCommand(reffSql, objConn1); 
  comboBox4.SelectedValue = Convert.ToString(rcmd.ExecuteScalar());

我使用了上面一个但没有工作

2 个答案:

答案 0 :(得分:0)

我假设您将在初始加载comboBox数据的同时使用DisplayMember和ValueMember填充comboBox。

初始加载:

您应该从表中检索Id和Name字段,并将其绑定到组合框。

//Loading comboBox3
SqlDataAdapter da = new SqlDataAdapter("select Id, Material from Master.Materialname", objConn1); 
DataTable dt = new DataTable(); 
da.Fill(dt); 
DataRow dr; 
dr = dt.NewRow(); 
comboBox3.DisplayMember = "Material"; 
comboBox3.ValueMember = "Id"; 
comboBox3.DataSource = dt; 

//Loading comboBox4
SqlDataAdapter da1 = new SqlDataAdapter("select Id, Process from Master.ProductionProcess", objConn1); 
DataTable dt1 = new DataTable(); 
da1.Fill(dt1); 
DataRow dr1; 
dr1 = dt1.NewRow(); 
comboBox4.DisplayMember = "Process"; 
comboBox4.ValueMember = "Id"; 
comboBox4.DataSource = dt1; 
objConn1.Close(); 

然后在combo3selectedIndex更改事件中,

if (Convert.ToInt32(comboBox3.SelectedValue) > 0)
    comboBox4.SelectedIndex = comboBox3.SelectedIndex;

comboBox4的selectedValue现在应该更改。

答案 1 :(得分:0)

    SqlDataAdapter da = new SqlDataAdapter("select Id, Material from Master.Materialname", objConn1); 
    DataTable dt = new DataTable(); 
    da.Fill(dt); 
    DataRow dr; 
    dr = dt.NewRow(); 
    comboBox3.DisplayMember = "Material"; 
    comboBox3.ValueMember = "Id"; 
    comboBox3.DataSource = dt; 

write below code on combobox3 changed event

    int newid = comboBox3.selectedvalue;

    //Loading comboBox4
    SqlDataAdapter da1 = new SqlDataAdapter("select Id, Process from Master.ProductionProcess and Id = " + newid , objConn1); 
    DataTable dt1 = new DataTable(); 
    da1.Fill(dt1); `enter code here`
    DataRow dr1; 
    dr1 = dt1.NewRow(); 
    comboBox4.DisplayMember = "Process"; 
    comboBox4.ValueMember = "Id"; 
    comboBox4.DataSource = dt1; 
    objConn1.Close();