Sunday, September 7, 2008

Programmatically Removing items from a list control

By Kevin Marshall

You can remove ListItems from List Control using server side code; this involves using the RemoveAt method of the Items property, this is shown in the following example.

Example 5

C#
DropDownList1.Items.RemoveAt(2);
VB
DropDownList1.Items.RemoveAt(2)

This line is removing the third (zero based remember) ListItem from the list.

This may not be of much use in a dynamically filled List Control because you can't be expected to know beforehand the index number of each ListItem in the list. For example, if you wanted to remove a ListItem that has the Text value of "Item 3" you need to find the index number of that item. The following code shows how this can be done.

Example 6

C#
for(int i=DropDownList1.Items.Count-1; i>-1; i--)
{
if(DropDownList1.Items[i].Text == "Item 3")
{
DropDownList1.Items.RemoveAt(i);
break;
}
}
VB
Dim i As Integer
For i = DropDownList1.Items.Count - 1 To 0 Step -1
If DropDownList1.Items(i).Text = "Item 3" Then
DropDownList1.Items.RemoveAt(i)
Exit For
End If
Next

Each line of this example is explained on an individual basis below:

VB
Dim i As Integer

This VB line declares an integer variable called i that will be used when looping through the ListItems in the Items collection.

C#
for(int i=DropDownList1.Items.Count-1; i>-1; i--)
VB
For i = DropDownList1.Items.Count - 1 To 0 Step -1

This line begins a for loop to loop through the Items collection. The loop starts on the last ListItem and loop backwards from there to the first item. The reason for this is when you delete an item from a collection you'recurrently looping through, an error will occur due to possibility of the loop continuing past the new collection count (this changes when you remove an item); by looping backwards this is not a problem.

C#
if(DropDownList1.Items(i).Text == "Item 3)
DropDownList1.Items.RemoveAt(i);
break;
VB
If DropDownList1.Items(i).Text = "Item 3" Then
DropDownList1.Items.RemoveAt(i)
Exit For

Within each pass through the loop, the Text value of the current ListItem is checked to see if it equals "Item 3". If it does, the items is removed using the RemoveAt method, passing the index number to remove using the i variable as an argument. Once the ListItem is removed the break (Exit For in VB) is called to exit the loop, as there is no point continuing if our work here is already done.
http://www.dnzone.com/showDetail.asp?TypeId=27&NewsId=671&LinkFile=page5.htm

ASP.Net Feeds