Click here to Skip to main content
16,019,152 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I have 3 foreach loop like...
C#
foreach (DropDownList drodown in pnlTextBoxes.Controls.OfType<dropdownlist>())
 {
  foreach (DropDownList drodown1 in pnlTextBoxes.Controls.OfType<dropdownlist>())
     {
     foreach (TextBox textBox in pnlTextBoxes.Controls.OfType<textbox>())
        {
        }
     }
}


I want this all dynamic contol into single foreach loop.
I dont have idea how to write can you send me code for that.
Posted
Updated 29-Nov-15 22:21pm
v2
Comments
CHill60 30-Nov-15 4:23am    
Why are you going through the dropdownlists twice?
Tomas Takac 30-Nov-15 4:54am    
What are you trying to do? Why are the loops nested? Where does the && operator come in?
Patrice T 30-Nov-15 15:11pm    
Explain what you want to do .

My guess is that you want to do something like this:
C#
foreach(Control cntrl in pnlTextBoxes)
{
    if(cntrl is DropDownList)
    {
       DropDownList ddl = cntrl as DropDownList;
       // handle DropDownList
    }
    else if (cntrl is TextBox)
    {
       TextBox tbx = cntrl as TextBox;
       // handle TextBox
    }
}
 
Share this answer
 
Comments
[no name] 30-Nov-15 23:21pm    
Was scrolling down to write exactly this, I think you nailed it. 5.
A foreach loop can only operate on one dimension of a single ienumerable type. To merge the lists you have you need to find a common denominator Type. In your case, the common denominator type of the first two in dropdownlist but if you include the textbox then the common denominator type is Control.

C#
List<control> controls = new List<control>();

controls.AddRange(pnlTextBoxes.Controls.OfType<dropdownlist>())
//etc</dropdownlist></control></control>

PS: you are aware that the first and second lists you have there are identical?

Another option is to select into the list using Linq:

C#
Type[] dynamicControlTypes = {typeof(DropDownList), typeof(TextBox), /*etc...*/);
foreach(Control c in pnlTextBoxes.Controls.Where(c=>dynamicControlTypes.contains(c.GetType))){

}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900