#  Sunday, March 09, 2008
Posted in  |  | 

One major downsides of using a checkbox in a GridView control to handle mass updates and deletes is that the state of the checkboxs will be lost when going to another page.

To work around this were going to have to write some code to save and load the state of the checkboxes.

You can download the files below.

 

 

The 1st thing we want to do is set up our GridView and a DataSource.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!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>Grid View Check Box Example</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="Gridview1" OnDataBound="Gridview1_OnDataBound" runat="server" Width="100%" OnPageIndexChanging="Gridview1_PageIndexChanging" AllowPaging="True" AutoGenerateColumns="False" DataKeyNames="recordID" DataSourceID="AccessDataSource1">
                <Columns>
                    <asp:BoundField DataField="recordID" HeaderText="recordID" InsertVisible="False" ReadOnly="True" SortExpression="recordID" />
                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:CheckBox ID="chkPerson" runat="server" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="firstName" HeaderText="firstName" SortExpression="firstName" />
                    <asp:BoundField DataField="lastName" HeaderText="lastName" SortExpression="lastName" />
                </Columns>
                <HeaderStyle HorizontalAlign="Left" />
            </asp:GridView>
            <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/gridviewCheckbox.mdb" SelectCommand="SELECT [recordID], [firstName], [lastName] FROM [record]"></asp:AccessDataSource>
            <br />
            <br />
            <asp:Button ID="bttnMassUpdate" runat="server" OnClick="bttnMassUpdate_Click" Text="Mass Update" /><br />
        </div>
    </form>
</body>
</html>

For those of you who are unfamiliar with grid views, The DataKeyNames property is set to the PrimaryKey column of your datasource and in this example its the recordID column.

The OnDataBound and OnPageIndexChanging properties are set to the name of the functions I created that I want called when these events are fired.

 

I used a AccessDataSource for this example because It would allow anyone to download and run this example without the need to install a SQL server.

The data in this Access Database was generated with http://www.generatedata.com/.

 

Now since we have our aspx page setup we need to choose a data structure that can hold the primary key for each select row. I chose a List for this task.

protected void Page_Load(object sender, EventArgs e)
   {
       if (!Page.IsPostBack)
       {
           List<int> list = new List<int>();
           Session["gridSave"] = list;
       }
   }

 

Now when we go to another page we need a way to store the primary key of each row that has been selected and to also remove any key that has been unselected.

private void saveValues()
{
    List<int> list = (List<int>)Session["gridSave"];
 
    foreach (GridViewRow row in Gridview1.Rows)
    {
        int id = (int)Gridview1.DataKeys[row.RowIndex].Value;
        bool chk = ((CheckBox)row.FindControl("chkPerson")).Checked;
 
        if (chk)
        {
            //see if we have a id added already
            if (list.Contains(id) == false)
            {
                list.Add(id);
            }
        }
        else
        {
            if (list.Contains(id))
            {
                list.Remove(id);
            }
        }
    }
 
    Session["gridSave"] = list;
}

 

Everytime we go to a new page we will also have to see if any checkboxes need to be checked

private void loadValues()
{
    List<int> list = (List<int>)Session["gridSave"];
 
    foreach (GridViewRow row in Gridview1.Rows)
    {
        int id = (int)Gridview1.DataKeys[row.RowIndex].Value;
        if (list.Contains(id))
        {
            CheckBox chkPerson = (CheckBox)row.FindControl("chkPerson");
            chkPerson.Checked = true;
        }
    }
}

 

The above functions are called from the GridViews PageIndexChanging and OnDataBound Events.

protected void Gridview1_PageIndexChanging(object sender, GridViewPageEventArgs e)
   {
       saveValues();
       Gridview1.PageIndex = e.NewPageIndex;
   }
 
   protected void Gridview1_OnDataBound(object sender, EventArgs e)
   {
       loadValues();
   }
Sunday, March 09, 2008 1:48:42 AM (Eastern Standard Time, UTC-05:00)   #     Comments [0] -

OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, i, strike, strong, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview
Advertisments
Archive
<November 2008>
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456
Statistics
Total Posts: 8
This Year: 7
This Month: 0
This Week: 0
Comments: 14
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Chris Newman
Sign In