C# Listbox Foreach

C# Listbox Foreach


   Here in this post we will see how to get values of listitems in listBox which are selected.

  <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" Height="112px" SelectionMode="Multiple">
            <asp:ListItem>Administrator</asp:ListItem>
            <asp:ListItem>Editor</asp:ListItem>
            <asp:ListItem>Publisher</asp:ListItem>
            <asp:ListItem>Coder</asp:ListItem>
            <asp:ListItem>Writer</asp:ListItem>
            <asp:ListItem>Designer</asp:ListItem>
        </asp:ListBox>&nbsp;<br />
        <br />
        &nbsp;<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
    </form>

Code behind C#.Net code

 protected void Button1_Click(object sender, EventArgs e)
    {
       

        foreach(ListItem li in ListBox1.Items)
        {
            if(li.Selected == true)
            {
                Response.Write(li.Text);
                 Response.Write("<Br/>");
            }
        }
       
    }


ListBox is collection of listitems that we can iterate using foreach loop.

Note: For best performance of an application use for loop instead of for each loop.

 

Currently rated 3.0 by 2 people

  • Currently 3/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5