Home > Enterprise >  C# Is this possible via While loop and ComboBox Values?
C# Is this possible via While loop and ComboBox Values?

Time:02-22

I have 43 Combox value's I'm trying to loop through and write to an XML. Here is part of the Code below that I can't see to get right.

                        int i = 1;
                        while (i < 44)
                        {
                            string Test = Controls["Track_"   i].Text;
                            w.WriteElementString("Track_Name", Test);
                            i  ;

What I'm expecting to be put in is following text from the ComboBoxes below all the way through Test_43.Text. I'm not sure what I'm doing wrong or if what I'm trying to do is even possible?

w.WriteElementString("Track_Name", Test_1.Text);
w.WriteElementString("Track_Name", Test_2.Text);
w.WriteElementString("Track_Name", Test_3.Text);
w.WriteElementString("Track_Name", Test_4.Text);

CodePudding user response:

Yes it is, and almost exactly as you have it written, from what I can tell. You are using ["Track_" i], while I think you want ["Test_" i] based on the final bit you posted.

I put this code inside a button on a test form (.NET 6.0 in case it matters) and it displays "Hello" and "World" on two text lines. My comboBox1.Text == "Hello" and comboBox2.Text == "World"

string myString = "";
for(int x = 1; x < 3; x  )
{
    myString  = Controls["comboBox"   x].Text   "\n";
}
MessageBox.Show(myString);

You could also do it a little easier like this:

int i = 1;
while (i < 44)
{
    w.WriteElementString("Track_Name", Controls["Test_"   i].Text);
    i  ;
}

CodePudding user response:

If you use Controls[] syntax then the control must be DIRECTLY contained by the Form. They won't be found if they are in a different container, like a Panel for instance.

An easier way is to use Controls.Find() with the "recurse" option which will SEARCH for the control by name no no matter how deeply nested it is:

for(int i=1; i<=43; i  )
{
    ComboBox cb = this.Controls.Find("Test_"   i, true).FirstOrDefault() as ComboBox;
    if (cb != null)
    {
        w.WriteElementString("Track_Name", cb.Text);
    }
}
  • Related