0

I have created dynamic controls on button click and I'm not able to retrieve values of dynamically created controls. I am getting values of dynamic controls inside a panel.

pnlDepartment is the Panel ID.

protected void btnValues_Click(object sender, EventArgs e)
{
    string strDDLValue = string.Empty;
    foreach (DropDownList ddl in pnlDepartment.Controls.OfType<DropDownList>())
    {
        strDDLValue = ddlName.SelectedItem.Text + "," + ddlLocation.SelectedItem.Text;
    }
}  

The strDDLValue has only first dropdown values and when it loops for the second time it still takes the first dropdown values and unable to get dynamic control values.

Please correct me if I'm making a mistake somewhere.

Updated code:

 string strDDLValue = string.Empty;
            foreach (DropDownList ddl in pnlDepartment.Controls.OfType<DropDownList>())
            {
                strDDLValue = ddl.SelectedItem.Text;
            }
Learner
  • 353
  • 9
  • 37

1 Answers1

0

You haven't used the dll variable. If the foreach loop in the pnlDeportment only contains the name. You will have to use this method.

protected void btnValues_Click(object sender, EventArgs e)   
{
    string strDDLValue = string.Empty;
    foreach (DropDownList ddl in pnlDepartment.Controls.OfType<DropDownList>())
    {
        strDDLValue = ddl.SelectedItem.Text
    }
}  

Other wise you must create two list that adds the dropdown for the name and one for the location.

init your lists at the init of your page.

List<DropDownList> ddlNames;
List<DropDownList> ddlLocations;

protected void btnValues_Click(object sender, EventArgs e)   
{ 
     if (dllNames.Count() == ddlLocations.Count())
     {
         for (int i = 0; i < ddlNames.Count(); i++)
         {
              strDDLValue = string.Format("{0},{1}", 
               ddlNames[i].SelectedItem.Text,
               ddlLocations[i].SelectedItem.Text );
         }
     }
}

Make sure you get the list of controls that you need by:

 int i = 0;
foreach (DropDownList ddl in pnlDepartment.Controls.OfType<DropDownList>())
{
    i++;
    ddl.SelectedItem.Text = string.Format("Found:{0}",i);
}
Ties Theunissen
  • 136
  • 2
  • 16
  • I'm creating two dynamic dropdown controls inside a panel and I'm unable to get values of dynamically created control values. Updated post with the code. – Learner Jan 08 '18 at 09:54
  • I have updated my anser, Please make sure that u get the list that u want. – Ties Theunissen Jan 08 '18 at 10:05