#  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] -

#  Tuesday, January 08, 2008
Posted in  | 

We all know how useful a hash table can be, but if you are using the .NET Framework 2.0 you should be using a Dictionary instead. A dictionary and a hash table in .NET 2.0 are very similar but with 1 main difference, a dictionary is faster because it does not need to box and unbox the data as a hash table would.

 

I made a simple program to see just how much faster a dictionary is than a hash table. I ran the test 20 times for each data set and the results were close each time. A GUID as the key and a boolean as the data.

This is the results of the last test for each dataset.

Time in Milliseconds for 100,000 keys Dictionary Hash Table
Inserting 34.41264 76.0970
Reading 18.9005 31.1648
Deleting 21.2474 30.4655

 

Time in Seconds for 10,000,000 keys Dictionary Hash Table
Inserting 6.5704143 26.9096540
Reading 3.1362891 5.6670613
Deleting 3.4623316 4.8830676

 

My comp specs

Vista Business 32bit, AMD 64 x2 5000+, 2GB ram

 

and now for the code I used. You can also download the project.  

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
 
namespace hashVsDictionary
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            #region init
 
            int num = 10000000;
            Guid[] guids = new Guid[num];
 
            Stopwatch s = new Stopwatch();
            s.Start();
 
            for (int i = 0; i < num; i++)
            {
                guids[i] = Guid.NewGuid();
            }
 
            s.Stop();
            Console.WriteLine("Data Creation = " + s.Elapsed);
            s.Reset();
 
            #endregion
 
            #region hash
 
            Hashtable hash = new Hashtable();
            s.Start();
            for (int i = 0; i < num; i++)
            {
                hash.Add(guids[i], true);
            }
            s.Stop();
            Console.WriteLine("Insert Hash = " + s.Elapsed);
            s.Reset();
 
            s.Start();
            for (int i = 0; i < num; i++)
            {
                bool b = Convert.ToBoolean(hash[guids[i]]);
            }
            Console.WriteLine("Extracting Hash = " + s.Elapsed);
            s.Reset();
 
            s.Start();
            for (int i = 0; i < num; i++)
            {
                hash.Remove(guids[i]);
            }
 
            Console.WriteLine("Removing Hash = " + s.Elapsed);
            s.Reset();
 
            #endregion
 
            #region dict
 
            Dictionary<Guid, bool> dict = new Dictionary<Guid, bool>();
            s.Start();
            for (int i = 0; i < num; i++)
            {
                dict.Add(guids[i], true);
            }
            s.Stop();
            Console.WriteLine("Insert Dictionary = " + s.Elapsed);
            s.Reset();
 
            s.Start();
            for (int i = 0; i < num; i++)
            {
                bool b = dict[guids[i]];
            }
            Console.WriteLine("Extracting Dict = " + s.Elapsed);
            s.Reset();
 
            s.Start();
            for (int i = 0; i < num; i++)
            {
                dict.Remove(guids[i]);
            }
            Console.WriteLine("Removing Dict = " + s.Elapsed);
            s.Reset();
 
            #endregion
 
            Console.ReadLine();
        }
    }
}
Tuesday, January 08, 2008 2:18:33 AM (Eastern Standard Time, UTC-05:00)   #     Comments [2] -

Advertisments
Archive
<August 2008>
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456
Statistics
Total Posts: 8
This Year: 7
This Month: 0
This Week: 0
Comments: 12
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