How to get value from listbox in ASP.Net using C#

 In this article i would like to show you how to:
-  Get value from listbox
-  set default selected to listbox
-   enable multiple selection mode for listbox.

In this case , I have a listbox and a Button. Whenever, I selected item(s) in the listbox and then click on Button, I will get value(s) from listbox. Please see example below:

Form design:

        <asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
                    < !-- SelectionMode= "Multiple"  mean  enable multi-select for listbox -->
                     <asp:ListItem Selected="true">Apple</asp:ListItem>
                     < !-- Selected= "true"  mean  set "Apple" as default selected value --> 
                     <asp:ListItem >Mango</asp:ListItem>
                     <asp:ListItem >Stawberry</asp:ListItem>
                     <asp:ListItem >grap</asp:ListItem>
                     <asp:ListItem>Orange</asp:ListItem>
                     <asp:ListItem>Water Milon</asp:ListItem>
                     <asp:ListItem>banana</asp:ListItem>
           </asp:ListBox>
           <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/>

Code Behind:

        protected void Button1_Click(object sender, EventArgs e)
        {
            string itemselected ="";
            // checking if listbox has no item
           if(ListBox1.Items.Count>0)
           {
               for (int i = 0; i < ListBox1.Items.Count; i++) {
                   if (ListBox1.SelectedItem.Selected) {
                       if (itemselected == "")
                       {
                          //get value from selected item to itemselected
                           itemselected = ListBox1.Items[i].Text;
                       }
                       else {
                           itemselected = "," + ListBox1.Items[i].Text;
                       }
                   }
               }
          }
        }
Hope this post will help you.
How to get value from listbox in ASP.Net using C# How to get value from listbox in ASP.Net using C# Reviewed by BeiLover on 11:58 PM Rating: 5

No comments:

Powered by Blogger.