如何根据从其他框中选择的文本更改动态创建的组合框的显示项

时间:2013-08-19 10:03:49

标签: c# windows forms

在C#(win-form)上制作我的项目时,我遇到了一个问题,我必须在每次单击添加按钮(button1)时动态生成2个组合框,并且我必须绑定第二个组合框与第一个框的索引更改,数据从数据库(sql server)检索。这是我的代码请帮助

    int _i = 0;int p = 0; int x=2; int y=0;
    private void button1_Click(object sender, EventArgs e)
    {
        for (int i = p; i < x; i++)
        {  ComboBox C1 = new ComboBox();
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter("select * from company ",con);
            DataSet ds = new DataSet();
            adp.Fill(ds, "Company");
            C1.DataSource = ds.Tables["Company"];
            C1.DisplayMember = "Company_Name";
            con.Close();

            C1.Location = new Point(160 + x, 30 * p + 10); ;
            C1.Name = "Combo - " + p;
            C1.Parent = this;

            p++;



        }

        x = x + 2;
        y++;
    }

1 个答案:

答案 0 :(得分:2)

如果其他人遇到同样的问题,请回答这个问题 -

创建组合框时,将selectedIndexChanged事件处理程序附加到它 -

private void button1_Click(object sender, EventArgs e)
    {
        ComboBox c1 = new ComboBox();
        Point loc1 = new Point(50, 80);
         Point loc2 = new Point(250, 80);
        c1.Name = "combobox1";              
        c1.Items.Add("ABC");
        c1.Items.Add("XYZ");
        c1.Items.Add("PQR");
        c1.SelectedIndexChanged += new EventHandler(combobox1__SelectedIndexChanged);
        c1.Location = loc1;

        ComboBox c2 = new ComboBox();
        c2.Name = "combobox2";
        c2.Location = loc2;

        this.Controls.Add(c1);
        this.Controls.Add(c2);
    }

    private void combobox1__SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox dummy = sender as ComboBox;
        if(dummy.SelectedItem == "ABC")
        ((ComboBox)dummy.Parent.Controls["combobox2"]).Items.Add("Your Intended items");


    }