为c# Windows窗体中动态创建的组合框调用SelectedIndexChanged事件

本文关键字:组合 调用 SelectedIndexChanged 事件 创建 Windows 窗体 动态 | 更新日期: 2023-09-27 17:50:16

我用c#创建了一个windows窗体。在那里我生成了2个动态组合框,即MajorComboHead和SubComboHead。我所做的是在创建控件时加载MajorComboHead。最后,我加载了SubComboHead在MajorComboHead SelectedIndexChanged事件(事件处理程序创建动态动态控件)。

SelectedIndexChanged事件工作正常,两个下拉框都加载良好,但问题是SubComboHead在MajorComboHead更改事件上加载项目,而不是加载。我无法调用MajorComboHead_SelectedIndexChanged事件在表单加载或在动态控件创建的时候。

请帮我一下。下面是MajorComboHead_SelectedIndexChanged事件和动态控件创建函数的代码:-

public void dynamicControls()
 {
.......................All about declaring and creating dynamic controls..................

        con2.Open();
        SqlDataAdapter adp1 = new SqlDataAdapter("select distinct * from MajorHead where(projectCode='" + projectId + "' AND (headName!='" + "Cash" + "' AND headName!='"+"Bank"+"'))", con2);
        DataSet ds1 = new DataSet();
        adp1.Fill(ds1, "MajorHead");
        MajorCombohead.DataSource = ds1.Tables["MajorHead"];
        MajorCombohead.DisplayMember = "headName";
        MajorCombohead.ValueMember = "headCode";
        con2.Close();
        MajorCombohead.SelectedIndexChanged += new EventHandler(MajorCombohead_SelectedIndexChanged);
}

public void MajorCombohead_SelectedIndexChanged(object sender, EventArgs e)
    {            
        ComboBox clicksave = sender as ComboBox;
        string savename = clicksave.Name;

        foreach (Control f1 in panel1.Controls)
        {
            if (f1.GetType() == typeof(ComboBox) && f1.Name == ("Maj" + savename))
            {                                      
                //.....................loading sub head........................
                foreach (Control f2 in panel1.Controls)
                {
                    if (f2.GetType() == typeof(ComboBox) && f2.Name == ("Sub" + savename))
                    {
                        con1.Open();
                        SqlDataAdapter adp2 = new SqlDataAdapter("select distinct * from SubHead where(majorHeadName='" + f1.Text + "' AND projectCode='" + projectId + "')", con1);
                        DataSet ds2 = new DataSet();
                        adp2.Fill(ds2, "SubHead");
                        int countMeNow = ds2.Tables[0].Rows.Count;
                        ((ComboBox)f2).DataSource = ds2.Tables["SubHead"];
                        ((ComboBox)f2).DisplayMember = "headName";
                        ((ComboBox)f2).ValueMember = "headCode";                           
                        con1.Close();
                    }
                }
                //.....................loading sub head........................

            }
        }

    }

为c# Windows窗体中动态创建的组合框调用SelectedIndexChanged事件

位置

MajorCombohead.SelectedIndexChanged += new EventHandler(MajorCombohead_SelectedIndexChanged);

加载MajorCombohead之前(声明变量,添加事件监听器,然后将其放在表单上)