This article shows you how to add items to a ListBox control using ListItem.
When you drag and drop a ListBox object onto your web form, there are many ways
to populate the ListBox. One of the easiest ways is to add items through the
items collection property in the properties tab.
But what if you want to populate the ListBox with data captured from other
places? You can use the ListItem object and then use the ListBox method
AddRange. The AddRange method is a member of the ListItemCollection class.
AddRange, adds the items in an array of System.Web.UI.WebControls.ListItem
objects to the collection.
The first thing you would have to do is create an array of ListItem. Then you
would have to assign values to the array members. Then add the ListItem array
to the ListBox with the AddRange method.
Let's try it out. Create a new solution and project as appropriate. Then drag a
ListBox object onto the webform. On the properties tab, find the ID property
and type in lbTest. Then look for the SelectionMode property and set it to
Multiple.
Go to the Items property and see the (Collection) field. Click the word
Collection and then click the ellipses button. This will open the ListItem
Collection Editor. By clicking on the Add button you could populate your
ListBox easily with the values you want. But our goal is to see something else
entirely. Click the cancel button to close the Editor.
Right click on the WebForm and choose the code menu item. To populate our
ListBox we need a ListItem. You could add each item to the ListBox one at a
time using the Add method.
lbTest.Items.Add("Roses");
But again, that doesn't show us what we are trying to see. We want to use the
AddRange method which requires a ListItem collection. So the first thing we do
is create an instance of a ListItem array. Go to the Page_Load event in the C#
code behind and type in the following line.
ListItem[] items = new ListItem[4];
Then we populate each item in the array with a text and value.
items[0] = new ListItem("Roses","Roses");
items[1] = new ListItem("Tulips","Tulips");
items[2] = new ListItem("Pansies","Pansies");
items[3] = new ListItem("Crocus","Crocus");
Next we add our ListItem collection to the ListBox.
lbTest.Items.AddRange(items);
Now we are complete. If we were to run this right now it would populate our
ListBox with the 4 values. Go ahead and try it now. Pretty simple right? Then
why did we need this article?
Because a lot of people try to do this and they get this error and they can't
figure out why? I have seen it many times with new programmers. They create
their ListItem correctly, but they get this error and it stumps them.
Object reference not set to an instance of an object.
We are going to cause you to get the error now. Change number 4 to a number 5
where you instantiated your ListItem array.
ListItem[] items = new ListItem[5];
Save, compile and run. You will get the ugly yellow screen with the Object
reference not set to an instance of an object error message. Why? It is because
when you tried to AddRange, you did not initialize all the members of the
array. The fifth item in the array items[4] is null. So when AddRange went to
the 5th item in the ListItem collection there wasn't anything there, so it
crashed.
Always check to see that all members of the array have a value. Another way to
populate the list box using the ListItem collection is to use the foreach loop.
Since the ListItem is a collection then you can iterate through the collection.
foreach (ListItem item in items)
lbTest.Items.Add(item);
Now that you have your ListBox populated, let's use the ListItem collection to
retrieve information from the ListBox. Because the selection mode property of
lbTest is multiple you need to iterate through its ListItem collection to
individually gather the needed information.
private void btnGo_Click(object sender, System.EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach(ListItem item in lbTest.Items)
if (item.Selected)
sb.Append(string.Format("{0}
",item.Text.ToString()));
lblItem.Text = sb.ToString();
}
Add a Label control to your WebForm, give it an ID property of lblItem. Drag a
Button control onto your form, with an ID property of btnGo and a Text property
of GO. Double click the Button control to create an Event Handler for the click
event.
Add a using statement to the top of the code. This is for the StringBuilder
object.
using System.Text;
Then in the Button click event type in the following code.
StringBuilder sb = new StringBuilder();
foreach(ListItem item in lbTest.Items)
if (item.Selected)
sb.Append(string.Format("{0}
",item.Text.ToString()));
lblItem.Text = sb.ToString();
This section of code first creates an instance of a StringBuilder object. This
is so we can most efficiently add strings together. Then we iterate through the
ListBox object, checking out the items that were selected. If any are selected,
then we explicitly convert the ListItem object to a string object and add it to
the StringBuilder object.
Once we are done reading all the members of the ListBox, we write the final
string to the Label control. Run the application, highlight multiple items in
the ListBox. (use the control button and the left click button on the mouse to
select multiple items). Click on the Go button and evaluate the Label control.
This article presented the ListItem Collection object and how to use it in a
ListBox object. Remember to initialize all the members of ListItem array to
prevent trying to access an object that isn't there. You also were presented
with the AddRange method of the ListBox control. Hope this hint makes your
programming easier.