Thursday, August 25, 2016

Using RadioButton Control in ASP.NET

RadioButton is a button control with Text that can be selected by the user.

In the case if user has to select one value from a group of values, we can add
more than one RadioButton to the webpage and provide the same GroupName.
GroupName is the property used for grouping values of RadioButtons.
In this case if a user select any one of the values, automatically it will clear
selection from the other values, if selected.

Programmatically we can know whether the RadioButton is selected by using
Checked property.

For specifying styles and other attributes there are many properties for a RadioButton
like any other web control. Also in an input form it can be set to validation controls for
validation.

If in case any logic has to be done on server side on its selection, we can set AutoPostBack
property to true and write the logic inside onCheckedChanged event.

Let me explain with an example of a webpage with two RadioButtons for
selecting the gender.

HTML Code (.aspx) :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Gender : "></asp:Label>
        <asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="gender"
            AutoPostBack="True" OnCheckedChanged="RadioButton_CheckedChanged" />
        <asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupName="gender"
            AutoPostBack="True" OnCheckedChanged="RadioButton_CheckedChanged" />
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="" Font-Bold="true" ForeColor="DarkGreen"></asp:Label>
    </div>
    </form>
</body>
</html>

C# Code (.aspx.cs) :


 protected void RadioButton_CheckedChanged(object sender, EventArgs e)
 {
        if (RadioButton1.Checked)
            Label2.Text = "You selected : " + RadioButton1.Text;
        else
            Label2.Text = "You selected : " + RadioButton2.Text;
 }

Output :



No comments:

Post a Comment