In this article I’ll explain how to use RadioButtons in asp.net GridView so that it becomes mutually exclusive so that user can select only one record.
Database
For this article I have used the Microsoft Northwind Database which you can download using the link below
Download Northwind Database
GridView Markup
<asp:GridView ID="GridView1" runat="server"
HeaderStyle-BackColor = "green"
AutoGenerateColumns = "false" Font-Names = "Arial"
OnPageIndexChanging = "OnPaging"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
AllowPaging = "true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server"
onclick = "RadioCheck(this);"/>
<asp:HiddenField ID="HiddenField1" runat="server"
Value = '<%#Eval("CustomerID")%>' />
</ItemTemplate>
</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>
You’ll notice I have place a RadioButton and a Hidden Field in the Itemtemplate. The Hidden Field stores the ID of the Customer whose significance is described later
Data Binding the GridView
The function below is used to databind the ASP.Net GridView
C#
private void BindGrid()
{
string strQuery = "select CustomerID,City,PostalCode" +
" from customers";
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand(strQuery);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
VB.Net
Private Sub BindGrid()
Dim strQuery As String = "select CustomerID,City,PostalCode" & _
" from customers"
Dim dt As New DataTable()
Dim strConnString As String = System.Configuration.ConfigurationManager _
.ConnectionStrings("conString").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter()
Dim cmd As New SqlCommand(strQuery)
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Sub
As you’ll notice I am simply executing SQL Query on the Customers table and binding the returned data to the ASP.Net GridView control
I am calling the above function in the Page Load event of the page like below
C#
protected void Page_Load(object sender, EventArgs e)
{
GetSelectedRecord();
BindGrid();
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
GetSelectedRecord()
BindGrid()
End Sub
Note here I am calling one more function GetSelectedRecord() which will be described later
Maintaining state of the RadioButtons
I am using ViewState variable to store the ID of the selected record. This helps me to remember the state of the RadioButtons. To achieve this I am using the following two functions
private void GetSelectedRecord()
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
RadioButton rb = (RadioButton)GridView1.Rows[i]
.Cells[0].FindControl("RadioButton1");
if (rb != null)
{
if (rb.Checked)
{
HiddenField hf = (HiddenField)GridView1.Rows[i]
.Cells[0].FindControl("HiddenField1");
if (hf != null)
{
ViewState["SelectedContact"] = hf.Value;
}
break;
}
}
}
}
VB.Net
Private Sub GetSelectedRecord()
For i As Integer = 0 To GridView1.Rows.Count - 1
Dim rb As RadioButton = DirectCast(GridView1.Rows(i).Cells(0) _
.FindControl("RadioButton1"), RadioButton)
If rb IsNot Nothing Then
If rb.Checked Then
Dim hf As HiddenField = DirectCast(GridView1.Rows(i).Cells(0) _
.FindControl("HiddenField1"), HiddenField)
If hf IsNot Nothing Then
ViewState("SelectedContact") = hf.Value
End If
Exit For
End If
End If
Next
End Sub
As the name suggests the above function’s job is to loop through all the records for the page of the ASP.Net GridView Control and if the RadioButton is checked, the ID stored in the corresponding Hidden Field is stored in the ViewState. This method is called in the page load event of the page.
C#
private void SetSelectedRecord()
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
RadioButton rb = (RadioButton)GridView1.Rows[i].Cells[0]
.FindControl("RadioButton1");
if (rb != null)
{
HiddenField hf = (HiddenField)GridView1.Rows[i]
.Cells[0].FindControl("HiddenField1");
if (hf != null && ViewState["SelectedContact"] != null)
{
if (hf.Value.Equals(ViewState["SelectedContact"].ToString()))
{
rb.Checked = true;
break;
}
}
}
}
}
VB.Net
Private Sub SetSelectedRecord()
For i As Integer = 0 To GridView1.Rows.Count - 1
Dim rb As RadioButton = DirectCast(GridView1.Rows(i) _
.Cells(0).FindControl("RadioButton1"), RadioButton)
If rb IsNot Nothing Then
Dim hf As HiddenField = DirectCast(GridView1.Rows(i) _
.Cells(0).FindControl("HiddenField1"), 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
The above function simply loops through the records in the current page of the ASP.Net GridView control and checks if the ID is the ViewState matches any of the rows. If it matches the corresponding RadioButton is checked. This function is called in the OnPageIndexChanging of the ASP.Net GridView control which is described below
C#
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
SetSelectedRecord();
}
VB.Net
Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind()
SetSelectedRecord()
End Sub
Client Side JavaScript
In order to make sure that only one RadioButton is checked the following JavaScript function needs to be placed in the head or body section (if using master pages) of the page.
<script type = "text/javascript">
function RadioCheck(rb) {
var gv = document.getElementById("<%=GridView1.ClientID%>");
var rbs = gv.getElementsByTagName("input");
var row = rb.parentNode.parentNode;
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>
This function makes sure that only one RadioButton is checked. This function is called up when the RadioButton is clicked by the user. For more information refer the GridView markup given above
To try the live demo click here.
Download the sample source code in VB.Net C# using the link below
GridViewRadioButtons.zip (4.66 kb)