Friday 24 August 2012

sample program for using foreach loop in asp.net


write the fallowing code in .aspx source file
<h2 style="color:Black">foreach loop</h2>  
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="red"></asp:Label>  
        <br /><br />  
        <asp:CheckBoxList   
            ID="CheckBoxList1"  
            runat="server"  
            ForeColor="AntiqueWhite"  
            BackColor="Black"  
            BorderColor="Orange"  
            BorderWidth="2"  
            BorderStyle="Double"  
            RepeatColumns="3"> 
            <asp:ListItem>Volly Ball</asp:ListItem>  
            <asp:ListItem>Cricket</asp:ListItem>  
            <asp:ListItem>Hockey</asp:ListItem>  
            <asp:ListItem>Basket Ball</asp:ListItem>  
            <asp:ListItem>Foot Ball</asp:ListItem>  
            <asp:ListItem>Swimming</asp:ListItem>
            </asp:CheckBoxList>  
        <br /><br />  
        <asp:Button ID="Button1" runat="server" Text="Select color" ForeColor="Blue" 
            onclick="Button1_Click" />

Write Fallowing code in button_click event

 protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = "You are selected: ";
        foreach (ListItem LI in CheckBoxList1.Items)
        {
            if (LI.Selected == true)
            {
                Label1.Text += LI+" "+"&"+" ";
            }
        }
    }


No comments: