In this article I will explain with an example, how to use
RadioButtons with
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.
Columns
GridView consist of one
TemplateField column and three
BoundField columns
The
TemplateField consists of an
ItemTemplate with two controls i.e.
RadioButton and
HiddenField.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" OnPageIndexChanging="OnPaging" AllowPaging="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:RadioButton ID="RadioButton1" runat="server" onclick="RadioCheck(this);" />
<asp:HiddenField ID="hfCustomerId" 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>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data;
Imports System.Configuration
Imports System.Data.SqlClient
Populating GridView with records from the Database
Page Load
Inside the Page Load event handler, the GetSelectedRecord function and BindGrid function are called.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.GetSelectedRecord();
this.BindGrid();
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.GetSelectedRecord()
Me.BindGrid()
End If
End Sub
BindGrid
Inside the
BindGrid method, the
GridView is populated with the records fetched
Customers table of
SQL Server database.
C#
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.Net
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
Maintaining state of the RadioButtons
GetSelectedRecord
Inside the
GetSelectedRecord, a FOR loop is executed over the
GridView rows and searches for a
RadioButton in each row.
If the
RadioButton is checked, it retrieves the
ID of the corresponding
HiddenField in the same row and stores it in the
ViewState.
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;
}
}
}
}
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
SetSelectedRecord
Inside this method, a FOR loop is executed over the
GridView rows and searches for a
RadioButton and a
HiddenField in each row.
If the value of the
HiddenField and value of the
ViewState is same then, the corresponding
RadioButton checked property set to
true.
C#
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 SetSelectedRecord()
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
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
Paging
Inside the
OnPageIndexChanging event handler, the
PageIndex property of the
GridView is updated with the new
Page Number which was clicked.
The
GridView is populated using the
BindGrid method which in-turn displays the new
GridView page.
Finally, the SetSelectedRecord method is called.
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
Client Side JavaScript
<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
Downloads