RadioButtonList within a GridView using the AJAX UpdatePanel

rafaelbelliard 1 Tallied Votes 558 Views Share

This simple but extremely useful trick explains how to hande a radiobutton within an ASP.NET gridview, without having to fiddle around with the sometimes cumbersome beast that javascript is. To avoid postbacks, we'll be using ASP.NET AJAX's updatepanel.

Basically, the logic is grabbing the sender (ie, the radiobutton checked), disabling every button currently checked, then checking the sender button.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebsite.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
    <title>RadioButton Demo</title>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="scriptManager" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                            <asp:GridView ID="gvAnswers" runat="server">
                                    <asp:TemplateField ItemStyle-Width="20px">
                                            <asp:RadioButton ID="rbAnswers" runat="server" 
                            <asp:Label ID="label1" runat="server" />

// C# code-behind 
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DemoWebsite
    public partial class Default : Page
        protected void Page_Load(object sender, EventArgs e)
            if (!Page.IsPostBack)
                // The data source to test against
                List<string> source = new List<string>
                                              "One", "Two","Three",
                gvAnswers.DataSource = source;

        protected void RbAnswersCheckedChanged(object sender, EventArgs e)
            // Unchecks previously selected rows
            foreach (GridViewRow oldrow in gvAnswers.Rows)
                ((RadioButton)oldrow.FindControl("rbAnswers")).Checked = false;

            // Checks the new row
            RadioButton rb = (RadioButton)sender;
            GridViewRow row = (GridViewRow)rb.NamingContainer;
            ((RadioButton)row.FindControl("rbAnswers")).Checked = true;
Member Avatar

Thank You :)!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.