Reputation: 199
I have created a windows form in C#. There I am generating 2 dynamic combobox, namely MajorComboHead and SubComboHead. What I have done is loaded MajorComboHead at time of controls creation. Eventually I have loaded SubComboHead on MajorComboHead SelectedIndexChanged Event (event handler created dynamically on dynamic controls creation).
SelectedIndexChanged Event is working fine and both the dropdown are loading fine, but the problem is SubComboHead is loading items on MajorComboHead change event and not on loading. I am unable to call the MajorComboHead_SelectedIndexChanged Event on form load or at the time of dynamic controls creation.
Kindly help me with this. Below is the code for MajorComboHead_SelectedIndexChanged Event nad dynamic controls creation function:-
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........................
}
}
}
Upvotes: 1
Views: 2926
Reputation: 1121
Place
MajorCombohead.SelectedIndexChanged += new EventHandler(MajorCombohead_SelectedIndexChanged);
Before load MajorCombohead (declare variable, add event listener and then place it on form).
Upvotes: 2