ASP.NET

Creating a Group of Radio Buttons Using RadioButtonList Control

Programmingempire

In this post on Creating a Group of Radio Buttons Using RadioButtonList Control, I will explain how to create several radio buttons as a group using a RadioButtonList control.

RadioButtonList Control

In short, a RadioButtonList control provides you a single-selection group of the radio buttons that you can use to create a web page. Meanwhile, you can add data items to the list by adding one item at a time. In addition, it is also possible to generate data items using data binding.

Basically, there are many properties of the RadioButtonList control that we can use to control its layout and style. As can be seen, we can use RepeatColumns, RepeatDirection, and RepeatLayout properties to display multiple items on the same row.

Furthermore, the SelectedValue, SelectedIndex, and SelectedItem properties help us retrieve the selection from the list. Also, there is an AutoPostBack property that submits the page as soon as the user selects an item. Besides, the Items collection represent all the data items contained in the list. Also, the Attributes collection allows us to specify an attribute for the control such as a CSS class.

Demonstration of Creating a Group of Radio Buttons Using RadioButtonList Control

The following code shows an example of Creating a Group of Radio Buttons Using RadioButtonList Control. To begin with, first, create a new ASP.NET project and add a Web Form to it. After that, add a CheckBoxList control, a Command Button, a RadioButtonList control, and a Label on the form. As an illustration, the ASPX file is shown below.

Since, we will add items to both the list controls dynamically, there is no need to do so in the ASPX file. Hence, leave the content part of the list boxes empty. However, we specify an event handler for the SelectedIndexChanged event. Thus, it will be called whenever a user makes a selection from the radio button list.

Besides the list controls, there is a button on the web page. As can be seen, the event handler of the click event of the Button keeps track of the items selected on the checkbox list. Lastly, we have a Label on the page that displays the selection performed on both the radio button list as well as the checkbox list.

Styling the Controls

In order to provide the styles for various controls on the page, we create four classes namely c1, c2, c3, and c4. Instead of specifying styles on the ASPX page, we add the respective CSS classes in the code behind file.

WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication29.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        .c1
        {
            color: lightcoral;
            background-color: crimson;
            padding: 10px;
            margin: 20px;
            border-radius: 6px;
        }
        .c2{
            background-color: darkorange;
            color: darkred;
            padding: 10px;
            margin: 20px;
            border-radius: 6px;
        }
        .c3{
            background-color: darkorange;
            color: darkred;
            padding: 10px;
            margin: 20px;
            border-radius: 6px;
            min-width:300px;
            height: 100px;
        }
       .c4{
            color: oldlace;
            background-color: darkred;
            padding: 10px;
            margin: 20px;
            border: 5px DarkMagenta solid;
            width: 400px;
            height:30px;
       }

    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div id="d1" runat="server">
                Select any number of emoloyees from the following list and assign a duty from the second list...
            </div>
            Select employee name from the list: 
            <asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList><br />
            <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
            <br />
            <br />
            Assign a Duty: 
            <asp:RadioButtonList ID="RadioButtonList1" runat="server" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
             </asp:RadioButtonList>
            <div id="d2" runat="server">
                <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
            </div>
        </div>
    </form>
</body>
</html>

Data Binding and Retrieving the Selected Values

The following code shows how we add items to the lists dynamically. In fact, the check box list is populated with the data that we retrieve from the database table. Therefore, first, we create a connection with the database. Then we fetch the data into a Dataset object. After that, we perform the data binding and also set the value of properties DataTextField and DataValueField of the check box list.

Analogous to the check box list, the radio button list also gets data items dynamically. However, we add data items to the radio button list using the Add() method of Items collection. Further, we use the SelectedItem property of the RadioButtonList control to retrieve the selection. Hence, we use the event handler for the SelectedIndexChanged event for this purpose.

Finally, we display the selection using the Text property of the Label. As has been noted, both of the lists should be filled initially with the data after checking the condition for the IsPostBack property of the Page. Otherwise, each postback will bring the same initial state of the web page.

WebForm1.aspx.cs

using System;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication29
{
public partial class WebForm1 : System.Web.UI.Page
{
String str1=””, str2=””;
SqlConnection cn;
SqlDataAdapter da;
DataSet ds;
public void Connect()
{
cn = new SqlConnection(@”Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=C:UsersKAVITADocumentsd1.mdf;Integrated Security=True;Connect Timeout=30″);
cn.Open();
da = new SqlDataAdapter(“select * from Emp”, cn);
ds = new DataSet();
da.Fill(ds, “Emp”);
}
public void BindCheckBoxList()
{
CheckBoxList1.DataSource = ds;
CheckBoxList1.DataTextField = “ename”;
CheckBoxList1.DataValueField = “empid”;
CheckBoxList1.DataBind();
}

    protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        str2 = RadioButtonList1.SelectedItem.Text;
        str1 = ViewState["staff"].ToString();
        Label1.Text += "The Duty " + str2 + " is assigned to <br/>" + str1;
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (ListItem item in CheckBoxList1.Items)
        {
            if (item.Selected)
            {
                str1 += item.Text.Trim() + "<br/>";
            }
            ViewState["staff"] = str1;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        RadioButtonList1.Attributes.Add("class", "c1");
        CheckBoxList1.Attributes.Add("class", "c2");
        d1.Attributes.Add("class", "c4");
        d2.Attributes.Add("class", "c3");

        RadioButtonList1.AutoPostBack = true;
        RadioButtonList1.RepeatColumns = 3;
        RadioButtonList1.RepeatDirection = RepeatDirection.Horizontal;
        RadioButtonList1.RepeatLayout = RepeatLayout.Table;

        if (!IsPostBack)
        {
            Connect();
            BindCheckBoxList();
        }
        if (!IsPostBack)
        {

            RadioButtonList1.Items.Add("Back Office Operations");
            RadioButtonList1.Items.Add("Data Backup");
            RadioButtonList1.Items.Add("Front Desk");
            RadioButtonList1.Items.Add("Telecalling");
            RadioButtonList1.Items.Add("Report Preparation");
            RadioButtonList1.Items.Add("Distribution");
            RadioButtonList1.Items.Add("Press Release Preparation");
        }
    }
}

}

Output

The following image shows the output of execution.

Example of Creating a Group of Radio Buttons Using RadioButtonList Control
Example of Creating a Group of Radio Buttons Using RadioButtonList Control

Further Reading

Parameter and ParameterCollection in ADO.NET

Database Manipulation Using DataGrid

Example of Button and Link Button Control in ASP.NET

Example of Chart Control in ASP.NET

Creating a DataTable from a DataReader in ASP.NET

Deleting a Record using DataGrid Control in ASP.NET

Edit a Record Using DataGrid Control in ASP.NET

Insert a Record Using ItemCommand Event in DataGrid

CRUD Operations with DataGrid in ASP.NET

Creating Columns in a DataGrid Control

XML Documents and DataSet in ASP.NET

Code Render Block in ASP.NET

ASP.NET Core Features and Advantages

Display Images Using DataList Control

Adding Images Using Image Control

Creating a Group of Radio Buttons Using RadioButtonList Control

Example of Button Control in ASP.NET

Using MD5 Hash Algorithm

ItemDataBound Event in DataList

More Features of DataList in ASP.NET

A Simple Example of Using a DataList Control in ASP.NET

Properties and Methods of DataList Control in ASP.NET

ASP.NET Practice Exercise

Exploring DataList Control in ASP.NET

Custom Validator Control in ASP.NET

Validation Summary Control in ASP.NET

Validation Controls Examples – RequiredFieldValidator, CompareValidator, and RangeValidator

An Example of Data Binding with RadioButtonList Control

Binding Data to Web Control in ADO.NET

Examples of AdRotator Control in ASP.NET

Examples of Validation Controls in ASP.NET

Overview of MVC architecture in ASP.NET

programmingempire

You may also like...