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.

 

Tags:

C# foreach loopC# Listbox ForeachC# Arraylist foreachc# arraylistListBox Asp.net Binding csharpC# Regular Expression Get Text Between BracketsListbox select multiplec# stringC# Break StatementAspnet Listbox Selectedindexchanged problems and solutionC# looping through array

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.