In this article I will explain with an example, how to use only one Radio Button from column in ASP.Net GridView control using C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
HTML Markup
The HTML Markup consists of:
GridView: – For displaying data.
The GridView has been assigned with OnPageIndexChanging event handler, the AllowPaging property has been set to TRUE and the DataKeyNames property has been set.
Columns
GridView consist of one TemplateField column and three BoundField columns.
TemplateField
The TemplateField consists of an ItemTemplate which contains an ASP.Net RadioButton control.
RadioButton – The RadioButton has been assigned with
JavaScript onclick event.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false"
OnPageIndexChanging="OnPaging" AllowPaging="true" DataKeyNames="CustomerID">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="rbCustomer" runat="server" onclick="RadioCheck(this);" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Populating GridView with records from the Database
Inside the Page Load event handler, the BindGrid method is called.
Inside the BindGrid method, the GridView is populated with the records fetched from Customers table of Northwind database.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
string query = "SELECT CustomerID, City, PostalCode FROM Customers";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Dim query As String = "SELECT CustomerID, City, PostalCode FROM Customers"
Using sda As SqlDataAdapter = New SqlDataAdapter(query, con)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Sub
Paging
Inside the OnPageIndexChanging event handler, the GetSelectedRecord method is called.
Then, the PageIndex property of the GridView is updated with the new Page Number which was clicked and the GridView is populated using the BindGrid method which in-turn displays the new GridView page.
Finally, the SetSelectedRecord method is called.
NoteThe GetSelectedRecord and SetSelectedRecord methods are explained later in the article.
C#
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
this.GetSelectedRecord();
gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
this.SetSelectedRecord();
}
VB.Net
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
Me.GetSelectedRecord()
gvCustomers.PageIndex = e.NewPageIndex
Me.BindGrid()
Me.SetSelectedRecord()
End Sub
Maintaining state of the RadioButtons
GetSelectedRecord
The GetSelectedRecord method is called inside the OnPageIndexChanging event handler.
Inside the GetSelectedRecord method, the current page GridView checked RadioButton row is referenced using the Linq query.
Finally, if the row is not null, the CustomerID is fetched using DataKeyNames property and stored in the ViewState.
ViewState variable is used to store the ID of the selected record which remembers the state of the RadioButtons, so that the values are preserved during PostBack.
C#
private void GetSelectedRecord()
{
GridViewRow selectedRow = (from GridViewRow row in gvCustomers.Rows
where (row.FindControl("rbCustomer") as RadioButton).Checked == true
select row).FirstOrDefault();
if (selectedRow != null)
{
ViewState["SelctedCustomer"] = gvCustomers.DataKeys[selectedRow.RowIndex].Values[0];
}
}
VB.Net
Private Sub GetSelectedRecord()
Dim selectedRow As GridViewRow = (From row In gvCustomers.Rows
Where TryCast(row.FindControl("rbCustomer"), RadioButton).Checked = True
Select row).FirstOrDefault()
If selectedRow IsNot Nothing Then
ViewState("SelctedCustomer") = gvCustomers.DataKeys(selectedRow.RowIndex).Values(0)
End If
End Sub
SetSelectedRecord
The SetSelectedRecord method is called inside the OnPageIndexChanging event handler.
Inside the SetSelectedRecord method, a check is performed whether the ViewState is not NULL and if yes then, current page GridView rows and the RadioButton is referenced.
Then, a check is performed whether the RadioButton is not NULL and if yes then the RadioButton Checked property is set to TRUE.
C#
private void SetSelectedRecord()
{
if (ViewState["SelctedCustomer"] != null)
{
RadioButton rbCustomer = (from GridViewRow row in gvCustomers.Rows
where gvCustomers.DataKeys[row.RowIndex].Values[0].ToString() == ViewState["SelctedCustomer"].ToString()
select (row.FindControl("rbCustomer") as RadioButton)).FirstOrDefault();
if (rbCustomer != null)
{
rbCustomer.Checked = true;
}
}
}
VB.Net
Private Sub SetSelectedRecord()
If ViewState("SelctedCustomer") IsNot Nothing Then
Dim rbCustomer As RadioButton = (From row In gvCustomers.Rows
Where gvCustomers.DataKeys(row.RowIndex).Values(0).ToString() = ViewState("SelctedCustomer").ToString()
Select TryCast(row.FindControl("rbCustomer"), RadioButton)).FirstOrDefault()
If rbCustomer IsNot Nothing Then
rbCustomer.Checked = True
End If
End If
End Sub
Unchecking RadioButton when one RadioButton is checked using JavaScript
If RadioButton is marked checked, the following
JavaScript function is called.
First, the GridView is referenced and then all the INPUT elements inside the GridView are referenced.
Then, a FOR loop is executed over the INPUT elements and check is made whether the INPUT element is RadioButton and if it is RadioButton then a confirmation is made that only one RadioButton is checked at a time.
If other RadioButton is checked, it unchecks those RadioButton inside the GridView.
<script type="text/javascript">
function RadioCheck(rb) {
var gvCustomers = document.getElementById("<%=gvCustomers.ClientID%>");
var rbCustomers = gvCustomers.getElementsByTagName("input");
for (var i = 0; i < rbCustomers.length; i++) {
if (rbCustomers[i].type == "radio") {
if (rbCustomers[i].checked && rbCustomers[i] != rb) {
rbCustomers[i].checked = false;
break;
}
}
}
}
</script>
Screenshot
Downloads