Iterating Through a List-Type Server Control

As many of you know, there are several List-Type server controls in ASP.Net, like the ListBox, DropDownList, CheckBoxList, and RadioButtonList. Since these controls are all of the same type, most of the same properties and methods work for each of them. The DropDownList and the RadioButtonList do have one drawback. Of the controls listed above, those two do NOT allow multiple selections, so they will not be addressed or included in this tutuorial. But for the Listbox and CheckBoxList, what you will learn here will become very handy.

First off, one basic way to iterate through a List Control is with the For/Next Loop, like this:

Dim li as ListItem For each li in YourListControl.Items If li.Selected = True Then ....Process your Data End If Next

You can see a ListBox code sample, using this technique here:
ListBox – Select All/Select None

If you were referring to an individual listItem in your programming, you would use the ‘SelectedItem’ property (either Text or Value) Inside, the loop, when you process the individual items, you can refer to each item in the list (li) and all it’s properties, directly, like:

  • li.Value
  • li.Text

Sometimes, though, you may want to process your data differently, and it may become necessary to use a different For/Next Loop, so, you can also use it this way:

Dim li as ListItem Dim x as Integer For x = 0 to YourListControl.Items.Count-1 If YourListControl.Items(x).Selected="True" Then ....Process your Data End If Next x

Continues…

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>