ASP.NET Web Forms RadioButton Control: Creating and Handling Radio Button Selections
Learn how to use the RadioButton control in ASP.NET Web Forms to create and handle groups of mutually exclusive choices. This tutorial explains how to create radio buttons, handle their selection, and retrieve the selected value from your web forms.
ASP.NET Web Forms RadioButton Control
Introduction to the RadioButton Control
The RadioButton control in ASP.NET Web Forms allows users to select a single option from a group of mutually exclusive choices. It's a server-side control, meaning it's processed on the server, and the selected value is sent to the server when the form is submitted. Radio buttons are commonly used in forms to collect user preferences or choices.
Creating a RadioButton Control
You can create a RadioButton control using either the Visual Studio drag-and-drop interface or by writing the HTML code directly in your ASPX file. Here's an example of creating a radio button using ASP.NET syntax:
Syntax
<asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="gender" />
Rendered HTML Output
<input id="RadioButton1" type="radio" name="gender" value="Male">Male
RadioButton Control Properties
The RadioButton control provides various properties to customize its appearance and behavior:
Property | Description |
---|---|
AccessKey |
Sets a keyboard shortcut. |
TabIndex |
Specifies the tab order. |
BackColor |
Sets the background color. |
BorderColor |
Sets the border color. |
BorderWidth |
Sets the border width. |
Font |
Sets the font style. |
ForeColor |
Sets the text color. |
Text |
Sets the text displayed next to the radio button. |
ToolTip |
Text displayed on hover. |
Visible |
Controls visibility. |
Height |
Sets the height of the radio button. |
Width |
Sets the width of the radio button. |
GroupName |
Specifies the name of the radio button group. Buttons with the same GroupName are mutually exclusive. |
Example: Handling RadioButton Selection
This example shows how to create a group of radio buttons and retrieve the selected value.
ASPX Code (WebControls.aspx)
<form id="form1" runat="server">
<asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="gender" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupName="gender" /><br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" /><br />
<asp:Label ID="genderId" runat="server"></asp:Label>
</form>
C# CodeBehind (WebControls.aspx.cs)
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
genderId.Text = RadioButton1.Checked ? "Your gender is Male" : "Your gender is Female";
}
}
}
Output
(A screenshot showing the radio buttons and the output label displaying the selected gender after the button click would be included here.)