1. Computing & Technology

Discuss in my forum

C# Programming Tutorial - Programming Advanced Winforms in C#

By , About.com Guide

1 of 10

Using Controls in Winforms - Advanced
WinForm with ComboBox

In this C# programming tutorial, I'll be concentrating on the advanced controls such as ComboBoxes, Grids, and ListViews and showing you the way you'll most likely use them. I'm not touching data and binding until a later tutorial.Let's begin with a simple control, a ComboBox.

ComboBox Winform Control

A "combo" is so called because it's a combination of a TextBox and a ListBox. It provides a variety of text editing methods all rolled up in one small control. A DateTimePicker control is just an advanced Combo with a panel that can pop up. But we'll stick to the basic ComboBox for now.

At the heart of a Combo is an items collection and the simplest way to populate this is drop a combo on the screen, select properties (if you can't see the properties windows, click View on the top Menu and then Properties Window), find items and click the ellipses button. You can then type in the strings, compile the program and pull the combo down to see choices.

  • One
  • Two
  • Three

Now stop the program and add a few more numbers: four, five.. up to ten. When you run it you'll only see 8 because that's the default value of MaxDropDownItems. Feel Free to set it to 20 or 3 and then run it to see what it does.

It's annoying that when it opens it says comboBox1 and you can edit it. That's not what we want. Find the DropDownStyle property and change DropDown to DropDownList.(It's a Combo!). Now there's no text and it's not editable. You can select one of the numbers but it always opens blank. How do we select a number to start with? Well it's not a property you can set at design time but adding this line will do that.

comboBox1.SelectedIndex =0;

Add that line in the Form1() constructor. You have to view the code for the form (in the Solution Explorer, right click on From1.cs and click View Code. Find InitializeComponent(); and add that line immediately after this.

If you set the DropDownStyle property for the combo to Simple and run the program you'll get nothing. It won't select or click or respond. Why? Because at design time you must grab the lower stretch handle and make the whole control taller.

Source Code Examples

On the next page : Winforms ComboBoxes Continued

©2012 About.com. All rights reserved.

A part of The New York Times Company.