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

Here, though, you will need to refer to the individual items in a different way. The ‘x’ variable in this case, is used to refer to the ListItems’ ordinal position (or index) in the List Control. Therefore, to process the individual items (li), you would do it like this:

  • YourListControl.Items(x).Value
  • YourListControl.Items(x).Text

With these two ways to iterate through your List Controls, you are now well-armed with very useful methods that will be come very handy in your future programming!

Related Posts:

  • No Related Posts
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!