C#: Using ListBoxes

ListBoxes are those same drop down components that you see in HTML forms. The same control called ComboBox works the same way although the appearance would be that of a 1 liner drop down box. Anyway, adding items to a ListBox object is pretty easy. Just do

?View Code CSHARP
1
2
MyListBox.Items.Add("Item 1");
MyListBox.Items.Add("Item 2");

But the code above will only add the labels that will apear within the ListBox. What if you want to have a ListBox that acts the same as a drop down HTML form component with a name and value attribute. You can create your own custom class with Name and Value exposed, place them inside an ArrayList object and pass it on to the ListBox’s DataSource property.

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ListBoxItem {
 
	public String Name;
	public String Value;
 
	public ListBoxItem(String name, String value) {
		Name = name;
		Value = value;
	}
 
	public override String toString() {
		return Name;
	}
 
}
 
ArrayList al = new ArrayList();
al.Add(new ListBoxItem("Item 1", "Value1");
al.Add(new ListBoxItem("Item 2", "Value2");
 
MyListBox.DataSource = al;

You can then get the selected name (and/or value) of the ListBox by doing this

?View Code CSHARP
1
((ListBoxItem) MyListBox.SelectedItem).Name

Donations appreciated. Every little $ helps. Or click Google +1

Related Posts with Thumbnails

tags: ,

2 Responses to “C#: Using ListBoxes”

  1. 1
    Sepp Forcher Says:

    There is an Error on Line 11:
    public override String toString()

    override will only work if you name “ToString()” correctly:
    public override String ToString()

  2. 2
    tech Says:

    @sepp: thanks for the heads up. i cannot verify this since it has been quite a long time since i touched .net but thank you for the correction.

Leave a Reply

Spam protection by WP Captcha-Free