Select One Row From a GridView

Select One Row From a GridView

by JBrooks 5. August 2009 16:53


I have a page where the user can select which users are active (using CheckBoxes), and also select one (only one) to be the administrator.  I put together this sample to show how I did it.  The sample uses technologies instead of user.  The picture below gives you an idea.  I didn't want to use the GridView "selected row" functionality because I didn't want to do a PostBack and I have another project where the user has to select 1 row per day where a day can take up 3 to 10 rows and there were many days in the grid.




using System;

using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SelectOne : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            ViewState["selectedBest"] = "ASP.Net";
    protected void bind()
        DataTable dt = new DataTable();
        dt.Columns.Add("Include", typeof(Boolean));
        dt.Columns.Add("Name", typeof(String));
        dt.Rows.Add(new Object[] { false, "C#" });
        dt.Rows.Add(new Object[] { false, "ASP.Net" });
        dt.Rows.Add(new Object[] { false, "SQL Server" });
        dt.Rows.Add(new Object[] { false, "VB.Net" });
        GridView1.DataSource = dt;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        if (e.Row.RowType != DataControlRowType.DataRow)
        // See if this matches our saved selection.
        if (e.Row.Cells[1].Text.Equals(ViewState["selectedBest"].ToString()))
            e.Row.Cells[2].Text = e.Row.Cells[2].Text.Replace("value", "checked value");
        // Set the value to the RowIndex so it is unique.
        e.Row.Cells[2].Text = e.Row.Cells[2].Text.Replace("{0}", e.Row.RowIndex.ToString());
    protected void btnSave_Click(object sender, EventArgs e)
        int total = 0;
        //Count of the number that our checked.
        foreach (GridViewRow gvr in this.GridView1.Rows)
            if (gvr.RowType != DataControlRowType.DataRow)
            if (((CheckBox)gvr.Cells[0].FindControl("cbSelected")).Checked)
        //Save the selected Best.
        ViewState["selectedBest"] = 
        //Normally you would be saving to the database here.
        this.lblMessage.Text = "You selected " + total.ToString() 
            + " with " + ViewState["selectedBest"].ToString() + " as the best.";
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SelectOne.aspx.cs" 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
<html xmlns="">
<head runat="server">
    <title>Test check all CheckBoxes</title>
    <script type="text/javascript" src="jquery-1[1].3.2.min.js"></script>
    <script type="text/javascript" language="javascript">
        function changeAllCheckBoxes(sender) {
            var gridViewRows = GetParentElementByTagName(sender, "TABLE").rows;
            for (var i = 1; i < gridViewRows.length; ++i) {
                gridViewRows[i].cells[0].childNodes[0].checked = sender.checked;
                //gridViewRows[i].cells[0].childNodes[1].style.display = 'none';
            return false;
        function GetParentElementByTagName(element, tagName) {
            var element = element;
            while (element.tagName != tagName)
                element = element.parentNode;
            return element;
    <form id="form1" runat="server">
    <div id="divp" style="text-align: left">
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        Caption="Pick Some Technologies"
            BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"
            CellPadding="4" onrowdatabound="GridView1_RowDataBound">
                <asp:TemplateField HeaderText="Include" SortExpression="Include">
                        <asp:CheckBox ID="CheckBox1" runat="server" 
                        onclick="changeAllCheckBoxes(this)" />
                        <asp:CheckBox ID="cbSelected" runat="server" />
                    <ItemStyle HorizontalAlign="Center" />
                <asp:BoundField DataField="Name" HeaderText="Technology" />
                <asp:TemplateField HeaderText="Best">
                        <input id="RBBest" type="radio" name="RBBest" value="{0}" />
                    <ItemStyle HorizontalAlign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
    <br />
        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
    <br />
    <asp:Label ID="lblMessage" runat="server" Text="Make selections and then click Save">


ASP.Net | GridView | Development