【问题标题】:how to change the display items of a dynamically created combo box according to the text selected from other box如何根据从其他框中选择的文本更改动态创建的组合框的显示项
【发布时间】:2013-08-19 10:03:48
【问题描述】:

在 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++;
    }

【问题讨论】:

  • 您能否详细说明bound the second combo box with the index change of the first box?你想怎么绑定它们?
  • 是的,实际上我希望当我从第一个组合框中选择任何文本时,第二个组合框中的文本应该像在数据库中一样相应更改
  • 如果我在数据库中的combox 1中有公司xyz并且它与子分支abc有关,那么,,当从第一个自动选择xyz时,第二个应该显示abc ...我想通过a绑定它们数据库中的表
  • 您的代码未显示组合框的 2 个数据源之间的任何连接。我们必须知道连接(例如第一个组合中的一些`Branch Id)与第二个组合中的相同)。
  • 是的,我知道,刚才我只为两个 comboboxex 连接了一个数据源,因为我无法修复如何将两个 comboboxex 相互连接的逻辑动态创建

标签: c# windows forms


【解决方案1】:

回答这个问题,以防万一其他人面临同样的问题--

在创建组合框时附加 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");


    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多