Friday, April 27, 2012

ListBox with Multi Selection in Asp.Net


ListBox with Multi Selection in Asp.Net

In general we use the DropDownList control in Asp.Net when the user needs to select an item from a list of available options, but there are situations where we need to allow the user to select more than one item from the available options, in these situations we can use the ListBox control.

Here is the design code in the .aspx page to place the ListBox and the various options, not that the SelectionMode property is set to Multiple, this will allow the user to select more than one option by pressing the CTRL (Control) key.

ListBox structure in .aspx page
<asp:ListBox
ID="lstBasePackageAsset"
runat="server"
SelectionMode="Multiple">
<asp:ListItem Value="0">-Select-</asp:ListItem>
<asp:ListItem Value="1">Name1</asp:ListItem>
<asp:ListItem Value="2">Name2</asp:ListItem>
<asp:ListItem Value="3">Name3</asp:ListItem>
</asp:ListBox>

Once the design code is in place, we can use the following code in the code-behind file to loop through the list items and find the ones which are selected. The selected items can be inserted into a database by using appropriate INSERT queries.

Reading the values (Multi-Select) from the ListBox & insert to the Database
for (int i = 0; i < lstNames.Items.Count; i++)
{
  if (lstNames.Items[i].Selected == true)
   {
sbInsertQuery.Append("insert into EMP_LIST (ID)VALUES (" + lstNames.Items[i].Value)");
    }
}

Once the items are inserted into the database, we will have to display them in the View mode, for a normal DropDownList control, we will use the SelectedValue or SelectedText property to set the selected value, but here we are dealing with multiple selection items, hence we need to run a loop of the list items and another loop on the selected ID’s and set the selected items in the list, here the code to set the selected items.

Selecting Multiple Items in the ListBox
strQuery = "SELECT ID FROM EMP_LIST;

DataSet
 dsNames = DataAccessLayer.GetDataSet(strQuery,"dtNames");

for (int j = 0; j < dsNames.Tables[“dtNames”].Rows.Count; j++)
{
  String strID = dsNames.Tables["dtNames"].Rows[i]["ID"].ToString()
  for (int k = 0; k < lstNames.Items.Count; k++)
  {
    if (lstNames.Items[k].Value == strID)
    {
      lstNames.Items[k].Selected = true;
    }
  }
}

That’s it we have seen how to restried/set multi-select items from an Asp.Net ListBox.

Search Flipkart Products:
Flipkart.com

3 comments:

Anonymous said...

thanks for easy explanation

Anonymous said...

Thanks for Explanation

Pratik said...

If you could include some images as well your blog will rock