none
Loop through combo boxes RRS feed

  • Question

  • I have couple of combo boxes named (combx_name1,combx_name2,combx_name3) and I need to go through each combo box to get its value using a loop as shown below.

    for(int I=0;I>3;i++)

    {

     string value = combx_name[i].text;

    }


    Saturday, January 11, 2020 5:40 AM

Answers

  • In case of small number of controls, try this:

    ComboBox[] a = new[] {  combx_name1, combx_name2, combx_name3 };

     

    foreach( ComboBox cb in a )

    {

       string value = cb.Text;

       // . . .

    }

     

    If you need the index, then use for instead of foreach.

    Check this too:

    for( int i = 1; i <= 3; ++i )

    {

       ComboBox cb = (ComboBox)Controls.Find( "combx_name" + i, true )[0];

       // . . .

    }



    Saturday, January 11, 2020 8:42 AM

All replies

  • In case of small number of controls, try this:

    ComboBox[] a = new[] {  combx_name1, combx_name2, combx_name3 };

     

    foreach( ComboBox cb in a )

    {

       string value = cb.Text;

       // . . .

    }

     

    If you need the index, then use for instead of foreach.

    Check this too:

    for( int i = 1; i <= 3; ++i )

    {

       ComboBox cb = (ComboBox)Controls.Find( "combx_name" + i, true )[0];

       // . . .

    }



    Saturday, January 11, 2020 8:42 AM
  • [...] combo box [...] get its value [...] as shown below.

    combx_name[i].text;

    The following warning is unrelated to the fact that you are looping through the comboboxes, but it is still worth keeping in mind because otherwise your code will not work and you will mistakenly blame the looping code for the failure: The .Text property of the ComboBox only returns the text if the user typed the text into the Combobox. But if the user selected one of the items from the drop-down list, then it is not copied into the .Text and the text will come back empty. In this case you need to use one of the .SelectedXxx properties (instead of the .Text property) to retrieve the item that was selected by the user.
    Sunday, January 12, 2020 1:11 PM
    Moderator
  • Noted. It is working perfectly. Thank you so much.
    Monday, January 13, 2020 7:27 AM
  • Hi Sampath Gamaarchchi,
    I am glad you have got your solution, we suggest that you mark it as the answer. So it can help other people who have the same problem find a solution quickly.
    Best Regards,
    Daniel Zhang


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, January 14, 2020 5:12 AM