C# Simplified, part 7: Working with WinForm Controls - Working with Combo boxes
(Page 5 of 6 )
Combo boxes enable you to select an item, but only one at a time. It consists of a text box with an arrow on the right side as shown in figure 7.5:

Figure 7.5
If you click the arrow, the combo box displays all the items within it as a drop-down menu, as shown in figure 7.6

Figure 7.6
The complete code for producing the above output is shown in the listing given below.
Listing 7.5
001: using System;
002: using System.Drawing;
003: using System.Windows.Forms;
004:
005: public class MyCombo: Form
006: {
007: // object of combo box created
008: ComboBox cb = new ComboBox();
009:
010: MyCombo()
011: {
012:
013: this.Controls.Add(cb);
014: cb.Items.Add("Visual Basic .NET");
015: cb.Items.Add("Visual C# .NET");
016: cb.Items.Add("Visual J# .NET");
017: cb.Text = "Please select";
018:
019: cb.Location = new Point(50,50);
020: cb.Size = new Size(200,70);
021: this.Text = "C# FAQ - Combo box Control";
022:
023: }
024:
025: public static void Main()
026: {
027: Application.Run(new MyCombo());
028: }
029: }
In the above code, items are added to the combo box using the Add() method of Items collection. You can also use the AddRange() method of Items collection as shown in listing 7.6:
Listing 7.6
cb.Items.AddRange(new object[3]
{"Visual Basic .NET","Visual C# .NET","Visual J# .NET});
Inside the method you are declaring an array object along with the specified values. If you need to add more items to the combo box you should update both the array index value and the items.
You can easily add items to a combo box if you are using Visual Studio .NET. Select the combo box and click the small ellipse on the right side of the Items property. Enter one value for each line and click the OK button to add the items to your combo box. After completing this process, you are ready to test your application by pressing the F5 key.
Next: Working with List boxes >>
More C# Articles
More By Anand Narayanaswamy