How to sort RadioButtonList items alphabetically in asp.net c#
As we know that RadioButtonList item is unsorted by default. But many times we want to sort our RadioButtonList items by alphabetically .so in this article, we will learn about how to sort RadioButtonList items alphabetically in asp.net c#
Source code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sortingradiobuttionlist.aspx.cs" Inherits="sortingradiobuttionlist" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset style="width:400px">
<legend>Unsort RadioButtonList items</legend>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>Agra</asp:ListItem>
<asp:ListItem>Lucknow</asp:ListItem>
<asp:ListItem>Delhi</asp:ListItem>
<asp:ListItem>Pune</asp:ListItem>
<asp:ListItem>Mumbai</asp:ListItem>
<asp:ListItem>Goa</asp:ListItem>
<asp:ListItem>Bahraich</asp:ListItem>
<asp:ListItem>Jhansi</asp:ListItem>
</asp:RadioButtonList>
</fieldset>
</div>
</form>
</body>
</html>
Code behind(c#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class sortingradiobuttionlist : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<ListItem> list = new List<ListItem>();
foreach (ListItem li in RadioButtonList1.Items)
{
list.Add(li);
}
List<ListItem> sorted = list.OrderBy(b => b.Text).ToList();
RadioButtonList1.Items.Clear();
foreach (ListItem li in sorted)
{
RadioButtonList1.Items.Add(li);
}
}
}
}
Out-Put:-
How to sort RadioButtonList items alphabetically in asp.net c#
Reviewed by NEERAJ SRIVASTAVA
on
7:48:00 PM
Rating:
No comments: