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

时间:2014-03-14 05:16:37

标签: c# .net winforms

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

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........................


            }
        }


    }

1 个答案:

答案 0 :(得分:2)

放置

MajorCombohead.SelectedIndexChanged += new EventHandler(MajorCombohead_SelectedIndexChanged);

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