How to perform foreach loop through RadioButtonList items in asp.net c#

RadioButtonList items foreach loop
RadioButtonList is an asp.net list web server control. radiobuttonlist control contains a collection of ListItem objects. we can iterate through this items collection using foreach loop.

the following asp.net c# example code demonstrate us how can we iterate through the radiobuttonlist items using foreach statement. the foreach statement cannot be used to add or remove items from the source collection. but we can change items any property value in a radiobuttonlist control using foreach loop. in this example we iterate through a radiobuttonlist items collection to display its items text, value and selected state using foreach loop.

we can break out of the foreach loop at any point using break keyword or step to the next iteration in the loop by using the continue keyword.
radiobuttonlist-foreach.aspx

<%@ Page Language="C#" AutoEventWireup="true"%>    
      
<!DOCTYPE html>
        
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    { 
        if(!Page.IsPostBack)
        {
            RadioButtonList1.Items.Add(new ListItem("Silver-eared Mesia", "1"));
            RadioButtonList1.Items.Add(new ListItem("Blue-winged Minla", "2"));
            RadioButtonList1.Items.Add(new ListItem("Bar-throated Minla", "3"));
            RadioButtonList1.Items.Add(new ListItem("White-eared Sibia", "4"));
            RadioButtonList1.Items.Add(new ListItem("Striated Yuhina", "5"));
        }

        Label1.Text = "";
        foreach(ListItem li in RadioButtonList1.Items)
        {
            Label1.Text += "<br />"+li.Text + " | " + li.Value;
            if (li.Selected)
            {
                Label1.Text += " | selected";
            }
        }
    }
</script>        
        
<html xmlns="http://www.w3.org/1999/xhtml">        
<head id="Head1" runat="server">        
    <title>asp.net c# radiobuttonlist foreach</title>
</head>        
<body>        
    <form id="form1" runat="server">        
    <div>        
        <h2 style="color:MidnightBlue; font-style:italic;">        
            asp.net c# example - radiobuttonlist foreach
        </h2>        
        <hr width="550" align="left" color="Gainsboro" />        
        <asp:Label       
            ID="Label1"       
            runat="server"      
            Font-Size="Large"
            Width="350"
            >      
        </asp:Label>      
        <br /><br />
        <asp:RadioButtonList 
            ID="RadioButtonList1"
            runat="server"
            RepeatDirection="Vertical"
            AutoPostBack="true"
            Border="1"
            BorderColor="LightGray"
            >
        </asp:RadioButtonList>  
    </div>        
    </form>        
</body>        
</html>
More asp.net examples