Tuesday, 15 April 2025

RadioButtonList Control Overview

Leave a Comment

In this walk-through, you will learn about RadioButtonList in detail, and you get answers of the following questions.

  1. What is RadioButtonList?
  2. How many Layout types?
  3. Which Layout is good to use?
  4. Generate a RadioButtonList with the following:
    1. List Collection Object C#
    2. Database Table data
    3. Manually ListItem
  5. Working Suggestion with RadioButtonList.
 

What is RadioButtonList?

RadioButtonList is a Form-Control of Standard section under the Asp.Net WebForms project template. Naming conventions for RadioButtonList is rbl. Using naming conventions helps you find objects on an aspx page very smartly and easily.

RadioButtonList render a group of Radio-Buttons by using data-source, manually added list-item. RadioButtonList allows users to select only one option (Radio -Button) from a list.

RadioButtonList Layout Types

RepeatDirection: Set rendering direction on browser. There are two types.

  • Horizontal
  • Vertical

RepeatLayout: Support the following types of layout.

  • Flow: Normal rendering.
  • OrderedList: This will display options with 1,2,3,4,5 numbering.
  • Table: Under Table layout.
  • UnorderedList: This will display a bulleted list •.
Which Layout is good to use?
  • Table: For perfect alignment and view. This will render using HTML tags.
  • Flow: It is very lightweight, and Custom CSS can be applied for beautification and alignment as per your current design.

Right Combination of RepeatDirection and RepeatLayout.

SR. NO. RepeatDirection RepeatLayout Remarks
1 Horizontal Flow Working fine.
2 Horizontal OrderedList Not Working, Error Message:
The UnorderedList and OrderedList layouts only support vertical layout.
3 Horizontal Table Working fine.
4 Horizontal UnorderedList Not Working, Error Message:
The UnorderedList and OrderedList layouts only support vertical layout.
5 Vertical Flow Working fine.
6 Vertical OrderedList Working fine.
7 Vertical Table Working fine.
8 Vertical UnorderedList Working fine.

Generate a RadioButtonList with the following.

1. List Collection Object C# to generate RadioButtonList

ASPX Page Code

<div style="border:1px solid black;width:50%;">
    <h2>Hardcoded Radiobutton List using C# List Collection Object</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblListObj"
        runat="server"
        onClick="HardCodeRbl()"
        ClientIDMode="Static">
    </asp:RadioButtonList>

    <br /><br />

    <span id="lblListObj" style="font:20px arial;"></span>
</div>

C# Code

// Create a list of fruits
List<string> fruits = new List<string>
{
    "Apple",
    "Banana",
    "Cherry",
    "Mango",
    "Orange",
    "Pineapple",
    "Strawberry"
};
rblListObj.DataSource = fruits;
rblListObj.DataBind();

JavaScript Code

<script>
    function HardCodeRbl() {
        var selected = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblListObj");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblListObj").innerHTML =
                "HardCoded List Collection Object Radiobutton List <br>Selected: <b>" + selected.value + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

Output


2. Database Table data used to generate RadioButtonList
ASPX Page Code
<div style="border:2px solid green; width:50%; margin-top:50px;">
    <h2>Database Table used to populate Radiobutton List</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblTableBase"
        runat="server"
        onClick="TableBaseRbl()"
        ClientIDMode="Static">
    </asp:RadioButtonList>

    <br /><br />

    <span id="lblTableBase" style="font:20px arial;"></span>
</div>
C# Code
// Database Table used to populate Radiobutton List
BindSportsList();

// BindSportsList Method
private void BindSportsList()
{
    // Database connection string
    string connStr = ConfigurationManager.ConnectionStrings["dbTestConstr"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand("SELECT SportID, SportName FROM tblSports", conn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        rblTableBase.DataSource = dt;
        rblTableBase.DataTextField = "SportName";
        rblTableBase.DataValueField = "SportID";
        rblTableBase.DataBind();
    }
}
Javascript Code
<script>
    function TableBaseRbl() {
        var selected = "";
        var selectedText = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblTableBase");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                selectedText = document.querySelector("label[for='" + inputs[i].id + "']").innerText;
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblTableBase").innerHTML =
                "Tablebase Radiobutton List Selected: <b>" + selected.value + " ----- " + selectedText + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

OUTPUT

3. Manually ListItem added to generated RadioButtonList

ASPX Page Code

<div style="border:2px solid red; width:50%; margin-top:50px;">
    <h2>Manually Added ListItem to populate Radiobutton List</h2>
    <hr />

    <asp:RadioButtonList
        ID="rblListItemManually"
        runat="server"
        onClick="rblListItem()"
        ClientIDMode="Static"
        RepeatDirection="Vertical"
        RepeatLayout="UnorderedList">

        <asp:ListItem Text="Bougainvillea" Value="1" />
        <asp:ListItem Text="Petunia" Value="2" />
        <asp:ListItem Text="Zinnia" Value="3" />
        <asp:ListItem Text="Sunflower" Value="4" />
        <asp:ListItem Text="Daffodil" Value="5" />
        <asp:ListItem Text="Lotus" Value="6" />

    </asp:RadioButtonList>

    <br /><br />

    <span id="lblListItem" style="font:20px arial;"></span>
</div>

NO C# Code Wirtten

Javascript Code

<script>
    function rblListItem() {
        var selected = "";
        var selectedText = "";

        // Read Hardcoded RadioButton List
        var rbl = document.getElementById("rblListItemManually");

        // Get all input elements
        var inputs = rbl.getElementsByTagName('input');
        var flag = false;

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].checked) {
                selected = inputs[i];
                selectedText = document.querySelector("label[for='" + inputs[i].id + "']").innerText;
                flag = true;
                break;
            }
        }

        // Check if a selection was made
        if (flag) {
            alert(selected.value);
            document.getElementById("lblListItem").innerHTML =
                "Manually Added ListItem Radiobutton List Selected: <b>" + selected.value + " ----- " + selectedText + "</b>";
        } else {
            alert('Please select an option.!');
            return false;
        }
    }
</script>

OUTPUT

Working Suggestion with RadioButtonList

1. Use CLientIDMode = “Static”. This will not generate a dynamic id of RadioButtonList control. This will help you use id easily in Javascript.

ClientIDMode="Static"

Note: The above settings are recommended for all Form-Controls.

2. Use Javascript for the event and get the selected value of the Radio Button. Try to use Maximum Javascript because this will reduce the server roundtrip and help to run the application faster.

3. For handling server-side events, you have to use the following settings.

  • AutoPostBack="true"
  • OnSelectedIndexChanged event method.

Happy Coding!

Best ASP.NET Core 9 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

 

0 comments:

Post a Comment