You are on page 1of 7

(https://www.aspsnippets.

com/)

ASP.Net GridView Radio Button Single Selection - Select only one RadioButton from Column (/Articles/ASPNet-GridView-Radio-
Button-Single-Selection---Select-only-one-RadioButton-from-Column.aspx)

 12 Mar 2013  19 Jan 2022  Mudassar Khan (/Authors/Mudassar-Khan.aspx)  9 Comments  166280 Views
 ASP.Net (/Categories/ASP.Net.aspx) GridView (/Categories/GridView.aspx) RadioButton (/Categories/RadioButton.aspx)

Here Mudassar Khan has explained with an example, how to use RadioButtons in ASP.Net GridView so that it becomes mutually exclusive using C# and VB.Net.

Mutually exclusive RadioButtons means when one RadioButton is selected, other RadioButton present in the GridView row will be unselected.

 Download Code Sample  View Demo

Download Free Word/PDF/Excel API (https://www.aspsnippets.com/Redirect.aspx?AdId=10567&RedirectUrl=https%3A%2F%2Fwww.e-iceblue.com%2FIntroduce%2Fspire-office-fo

 (https://www.facebook.com/sharer/sharer.php?u=https%3a%2f%2fwww.aspsnippets.com%2fArticles%2fASPNet-
GridView-Radio-Button-Single-Selection---Select-only-one-RadioButton-from-Column.aspx) (https://twitter.com/share?
url=https%3a%2f%2fwww.aspsnippets.com%2fArticles%2fASPNet-GridView-Radio-Button-Single-Selection---Select-only-one-
RadioButton-from-Column.aspx&text=ASP.Net GridView Radio Button Single Selection - Select only one RadioButton from
Column) (whatsapp://send?text=Please check this out at ASPSnippets!%0Ahttp://aspsnip.pet/407)

In this article I will explain with an example, how to use RadioButtons in ASP.Net GridView so that it becomes mutually exclusive using C# and VB.Net.

Mutually exclusive RadioButtons means when one RadioButton is selected, other RadioButton present in the GridView row will be unselected.

Database

Here I am making use of Microsoft’s Northwind Database. The download and install instructions are provided in the following article.

Download and install Northwind Database (https://www.aspsnippets.com/Articles/Install-Microsoft-Northwind-and-Pubs-Sample-databases-in-SQL-Server-Managemen


t-Studio.aspx)

HTML Markup

The HTML Markup consists of an ASP.Net GridView with three BoundField columns and one TemplateField column. Paging has been enabled for the GridView control b
y setting the AllowPaging property to True.

A RadioButton and a Hidden Field is placed inside the ItemTemplate of TemplateField column. The Hidden Field will be used to stores the ID of the Customer.

The RadioButton has been assigned with JavaScript OnClick event handler.

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="OnPaging" AllowPaging="tru


e">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" onclick="RadioCheck(this);" />
# ( )
<asp:HiddenField ID="hfCustomerId" runat="server" Value='<%#Eval("CustomerID")%>' />
</ItemTemplate>
(https://www.aspsnippets.com/)
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID" />
<asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
<asp:BoundField ItemStyle-Width="150px" 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 the GridView

Inside the Page Load event, the GridView is populated with records from the Customers Table of the Northwind Database.

 Note: The GetSelectedRecord method is also called inside the Page Load event. It will be described later in the article.

C#

protected void Page_Load(object sender, EventArgs e)


{
if (!this.IsPostBack)
{
this.GetSelectedRecord();
this.BindGrid();
}
}

private void BindGrid()


{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand())
{
string query = "SELECT CustomerID,City,PostalCode FROM Customers";
cmd.CommandText = query;
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
}

VB N
VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load


(https://www.aspsnippets.com/)
If Not Me.IsPostBack Then
Me.GetSelectedRecord()
Me.BindGrid()
End If
EndSub

Private Sub BindGrid()


Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand()
Dim query As String = "SELECT CustomerID,City,PostalCode FROM Customers"
cmd.CommandText = query
cmd.Connection = con
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End Using
End Using
End Using
End Using
End Sub

Implement Paging in GridView

The OnPaging event handles the Pagination for the GridView.

Inside the OnPaging event handler, the GridView’s PageIndex property is updated and the GridView is again populated using the BindGrid method.

Finally, the SetSelectedRecord method is called.

 Note: The SetSelectedRecord method is called inside the OnPageIndexChanging event. It will be described later in the article.

C#

protected void OnPaging(object sender, GridViewPageEventArgs e)


{
gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
this.SetSelectedRecord();
}

VB.Net

Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)


gvCustomers.PageIndex = e.NewPageIndex
Me.BindGrid()
Me.SetSelectedRecord()
End Sub

Maintaining state of the RadioButtons

The GetSelectedRecord method

The GetSelectedRecord method is called inside the Page Load event.

Inside the GetSelectedRecord method a loop is executed over the current page GridView rows and the RadioButton is referenced.

Then a check is performed if the RadioButton is checked, and if the RadioButton is checked then the ID stored in the corresponding Hidden Field is stored in the ViewSta
te.

 Note: ViewState variable is used to store the ID of the selected record which remembers the state of the RadioButtons, so that the v
alues are preserved during PostBack.
The SetSelectedRecord method
(https://www.aspsnippets.com/)
The SetSelectedRecord method is called inside the OnPageIndexChanging event.

Inside the SetSelectedRecord method, a loop is executed over the current page GridView rows and the RadioButton and HiddenField are referenced.

Then a check is performed whether the ViewState is not NULL and RadioButton value is equal to the ViewState value, and if yes then the RadioButton Checked property
is set to TRUE.

C#

private void GetSelectedRecord()


{
for (int i = 0; i < gvCustomers.Rows.Count; i++)
{
RadioButton rb = (RadioButton)gvCustomers.Rows[i].Cells[0].FindControl("RadioButton1");
if (rb != null)
{
if (rb.Checked)
{
HiddenField hf = (HiddenField)gvCustomers.Rows[i].Cells[0].FindControl("hfCustomerId");
if (hf != null)
{
ViewState["SelectedContact"] = hf.Value;
}

break;
}
}
}
}

private void SetSelectedRecord()


{
for (int i = 0; i < gvCustomers.Rows.Count; i++)
{
RadioButton rb = (RadioButton)gvCustomers.Rows[i].Cells[0].FindControl("RadioButton1");
if (rb != null)
{
HiddenField hf = (HiddenField)gvCustomers.Rows[i].Cells[0].FindControl("hfCustomerId");
if (hf != null && ViewState["SelectedContact"] != null)
{
if (hf.Value.Equals(ViewState["SelectedContact"].ToString()))
{
rb.Checked = true;
break;
}
}
}
}
}

VB.Net

Private Sub GetSelectedRecord()


For i As Integer = 0 To gvCustomers.Rows.Count - 1
Dim rb As RadioButton = DirectCast(gvCustomers.Rows(i).Cells(0).FindControl("RadioButton1"), RadioButton)
If rb IsNot Nothing Then
If rb.Checked Then
Dim hf As HiddenField = DirectCast(gvCustomers.Rows(i).Cells(0).FindControl("hfCustomerId"), HiddenField)
If hf IsNot Nothing Then
ViewState("SelectedContact") = hf.Value
End If
Exit For
End If
End If
Next
End Sub

Private Sub SetSelectedRecord()


For i As Integer = 0 To gvCustomers.Rows.Count - 1
Dim rb As RadioButton = DirectCast(gvCustomers.Rows(i).Cells(0).FindControl("RadioButton1"), RadioButton)
(https://www.aspsnippets.com/)
If rb IsNot Nothing Then
Dim hf As HiddenField = DirectCast(gvCustomers.Rows(i).Cells(0).FindControl("hfCustomerId"), HiddenField)
If hf IsNot Nothing And ViewState("SelectedContact") IsNot Nothing Then
If hf.Value.Equals(ViewState("SelectedContact").ToString()) Then
rb.Checked = True
Exit For
End If
End If
End If
Next
End Sub

Client Side JavaScript

When a RadioButton inside the GridView is selected, all the Input elements are referenced using the GridView control.

Then a loop is executed over all the input elements and its type is checked. If the input type is radio and the RadioButton is checked and it is not the current selected Ra
dioButton then its Checked property is set to False.

<script type="text/javascript">
function RadioCheck(rb) {
var gv = document.getElementById("<%=gvCustomers.ClientID%>");
var rbs = gv.getElementsByTagName("input");
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "radio") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
</script>

Screenshot

Demo

 View Demo

D l d
Downloads

 Download Code Sample


(https://www.aspsnippets.com/)

Download Free Word/PDF/Excel API (https://www.aspsnippets.com/Redirect.aspx?AdId=10567&RedirectUrl=https%3A%2F%2Fwww.e-iceblue.com%2FIntroduce%2Fspire-office-fo

 Related Articles

Display Images in GridView Control using the path stored in SQL Server database (/Articles/Display-Images-in-GridView-Control-using-the-path-
stored-in-SQL-Server-database.aspx)
Here Mudassar Ahmed Khan has described how to store images on disk and their path in images and then display them in GridView control in
 ASP.Net. Thus making your own Image or Picture Gallery

 Comments

No comments have been added to this article.

 Add Comments

 You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment
Please note that all comments are moderated and will be deleted if they are
Not relavant to the article
Spam
Advertising campaigns or links to other sites
Abusive content.

Please do not post code, scripts or snippets.

Name

Name

Email

Email

Comment
Comment
(https://www.aspsnippets.com/)

Security code:

I declare, I accept the site's Privacy Policy


(/PrivacyPolicy.aspx).

 Add Comment

What our readers say

 Uzair Aziz
You explain all the things in a simple manner. Your way of explaining things are really commendable.

 

© 2022 www.aspsnippets.com (https://www.aspsnippets.com/) All rights reserved | Privacy Policy (/PrivacyPolicy.aspx) | Powered by Excelasoft Solutions
(http://www.excelasoft.com/)

 (https://www.facebook.com/pages/ASPSnippets/306994206006035) 
(https://plus.google.com/110371172807820981480) 
(https://twitter.com/aspsnippets)  (/Rss.ashx)

You might also like