A ComboBox is a very useful component in any C# Windows application. It enables a form’s user to select information from a drop-down list. For example, in an application used to arrange delivery of an item the user should be allowed to choose the day of the week.
A ComboBox provides a simple way of doing this. However, in an example such as this there is one key issue: the day of the week changes according to the language being used (the English Monday is Lundi in French and Lunes in Spanish). So, rather than teach every user English the programmer may create a dynamic ComboBox whose contents change according the language being used.
Creating the ComboBox
As well as the ComboBox the user will need some way of selecting the language to be used. Radio buttons provide a suitable way of doing this:
The code will also need to contain the days of the week. In this example these are stored in three arrays. These arrays will be used to load the ComboBox according to which radio button is selected:
The ComboBox can then be added to the form:
As can the radio buttons:
Radio buttons for French and Spanish can be created in a similar way, although the coordinates given for the location (in x and y) will have to be different. If the form is compiled at this point then the ComboBox and radio buttons will be visible but will not actually do anything yet. The next stage, therefore, is to populate the ComboBox and assign actions to the radio boxes (so that the ComboBox is updated).
Populating (and Repopulating) the ComboBox
The ComboBox will be populated, cleared and then repopulated with the contents of the three arrays (for English, French and Spanish). Creating a new function will enable this to be done:
The function clears the ComboBox and then adds the items listed in an array passed to it. The programmer can then use this to set the initial state of the form:
This will check the “English” radio button and populate the ComboBox with the list ofEnglish days. The contents of the ComboBox will not actually change yet. For that some more functions are required:
And then these functions can be assigned to the radio buttons:
Now, if the form is compiled, the ComboBox will be populated with the correct days for the language selected.
Summary
Once a programmer has added a new ComboBox object to a C# Windows application it can be populated with the contents of an array by using the “AddRange” method. The programmer can repopulate it by first using the “Clear” method and then reusing “AddRange” with a different array.