Every time you want to have a multiple selection in a List Box, you have to write the same repetitive code again and again. Here is a nice utility method that you can embed into your web applications and use it by a simple method call to select multiple items inside a List Box:
/// <summary>
/// Selects multiple items in a ListBox control
/// </summary>
/// <remarks>
/// This method starts by validationt the two input parameters:
/// 1. <paramref name="lst" />
/// 2. <paramref name="items" />
/// The first parameter is the <see cref="System.Web.UI.WebControls.ListBox"/> whose elements
/// are to be selected. The second parameter is simply an array of <see cref="System.String"/>s
/// that represent the items that are to be selected inside the <paramref name="lst" />.
/// </remarks>
/// <param name="lst">ListBox to select its items</param>
/// <param name="items">Array of <see cref="System.String" />s</param>
private void SelectMultipleItems(ListBox lst, string[] items)
{
// Loop through the items of the array containing
// items to be selected
for(int i=0; i<items.Length; i++)
{
// Loop through the items inside the listbox
// break whenever you find the item serching for
foreach(ListItem lt in lst.Items)
{
// compare the item coming from the array
// to the one coming from the listbox
if (lt.Value == items[ i ])
{
lt.Selected = true;
break;
}
}
}
}
Hope this helps,
Regards
Tags: