Wednesday, 5 December 2012

ListBox multiple Selected Values C# ASP.NET

ListBox multiple Selected Values C# ASP.NET

Step1) Add Listbox to aspx page
             Add sample data  as shown below

 <asp:ListBox ID="ListBox1" AutoPostBack="false" runat="server" Height="135px" Width="167px" SelectionMode="Multiple">
            <asp:ListItem Value="Mon">Monday</asp:ListItem>
            <asp:ListItem Value="Tue">Tuesday</asp:ListItem>
            <asp:ListItem Value="Wed">WednesDay</asp:ListItem>
            <asp:ListItem Value="Thu">ThursDay</asp:ListItem>
            <asp:ListItem Value="Fri">FriDay</asp:ListItem>
            <asp:ListItem Value="Sat">SaturDay</asp:ListItem>
            <asp:ListItem Value="Sun">Sunday</asp:ListItem>
        </asp:ListBox>

make Selectionmode to Multiple and Autopostback to false, because in this case no need of postback (for each selection)

Step2) Add Button Control
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

Step 3) Add Label Control  for selected values display.
<asp:Label ID="Label1" runat="server" Text="Label" Width="600px" Height="150px"></asp:Label>
      
Step 4) on Button Click Event Hadler
protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
           foreach(ListItem li  in ListBox1.Items)
           {
               Label1.Text += (li.Selected) ? "Day:" + li.Value : "";
           }
        }

all selected dates will be added to Label1

for ex:output Day:WedDay:FriDay:SatDay:Sun
How to get Multiple values selected in ListBox ASP.NET C#

No comments:

Post a Comment