Select One Row From a GridView

I have a page where the user can select which users are active (using check boxes), 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 the 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.

pickone thumb
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";
            
            bind();
        }
    }

    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;
        GridView1.DataBind();
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType != DataControlRowType.DataRow)
            return;

        // 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)
                continue;

            if (((CheckBox)gvr.Cells[0].FindControl("cbSelected")).Checked)
                total++;
        }

        //Save the selected Best.
        ViewState["selectedBest"] = 

            this.GridView1.Rows[Convert.ToInt32(Request.Form["RBBest"])].Cells[1].Text;

        //Normally you would be saving to the database here.

        this.lblMessage.Text = "You selected " + total.ToString() 

            + " with " + ViewState["selectedBest"].ToString() + " as the best.";
        bind();
    }
}




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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<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;
        }
    </script>

</head>

<body>
    <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">
            <Columns>
                <asp:TemplateField HeaderText="Include" SortExpression="Include">
                    <HeaderTemplate>
                        <asp:CheckBox ID="CheckBox1" runat="server" 
                        onclick="changeAllCheckBoxes(this)" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="cbSelected" runat="server" />
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
                <asp:BoundField DataField="Name" HeaderText="Technology" />
                <asp:TemplateField HeaderText="Best">
                    <ItemTemplate>
                        <input id="RBBest" type="radio" name="RBBest" value="{0}" />
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Center" />
                </asp:TemplateField>
            </Columns>
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
        </asp:GridView>
    </div>
    <br />
    <div>
        <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
    </div>
    <br />
    <asp:Label ID="lblMessage" runat="server" Text="Make selections and then click Save">
    </asp:Label>
    </form>
</body>
</html>

Leave a Comment

Your email address will not be published. Required fields are marked *