Sunday, August 28, 2011

Persisting CheckBox State While Paging in GridView Control

grid

Default.aspx
----------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CheckBoxPersistGridView.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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView ID="gvCustomers" PageSize="3" AllowPaging="true" OnPageIndexChanging="gvCustomersPageChanging" runat="server" AutoGenerateColumns="false">
    
    <Columns>
    
    <asp:TemplateField>
    <ItemTemplate>
    <asp:CheckBox ID="chkSelect" runat="server" />
    </ItemTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="First Name">
    <ItemTemplate>
    <%# Eval("CatID") %>
    </ItemTemplate>
    </asp:TemplateField>
    
     <asp:TemplateField HeaderText="Last Name">
    <ItemTemplate>
    <%# Eval("CatName") %>
    </ItemTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="RowIndex">
    <ItemTemplate>
    <%# Container.DisplayIndex  %>
    </ItemTemplate>
    </asp:TemplateField>
    
      <asp:TemplateField HeaderText="DataItemIndex">
    <ItemTemplate>
    <%# Container.DataItemIndex  %>
    </ItemTemplate>
    </asp:TemplateField>
    
    </Columns>
    
    </asp:GridView>
    
    </div>
    </form>
</body>
</html>
Default.aspx.cs
--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.MobileControls;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace CheckBoxPersistGridView
{
    public partial class Default : System.Web.UI.Page
    {
        public const string SELECTED_CUSTOMERS_INDEX = "SelectedCustomersIndex"; 
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack)
            {
                BindData();
            }
        }
        private void BindData()
        {
            SqlConnection conn = new SqlConnection(@"Data Source=truefaster\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            conn.Open();
            SqlCommand cmd = new SqlCommand("select CatID,CatName from Category",conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "Category");
            gvCustomers.DataSource = ds.Tables["Category"];
            gvCustomers.DataBind();
            //using(var db = new  NorthwindDataContext())
            //{
                
            //    gvCustomers.DataSource = from c in db.Categories
            //                             select c; 
            //    gvCustomers.DataBind();
            //}
            RePopulateCheckBoxes(); 
        }
        private void RePopulateCheckBoxes()
        {
            foreach (GridViewRow row in gvCustomers.Rows)
            {
                var chkBox = row.FindControl("chkSelect") as CheckBox;
                IDataItemContainer container = (IDataItemContainer)chkBox.NamingContainer;
                if (SelectedCustomersIndex != null)
                {
                    if (SelectedCustomersIndex.Exists(i => i == container.DataItemIndex))
                    {
                        chkBox.Checked = true;
                    }
                }
            }
        }
        protected void gvCustomersPageChanging(object sender, GridViewPageEventArgs e)
        {
            foreach(GridViewRow row in gvCustomers.Rows)
            {
                var chkBox = row.FindControl("chkSelect") as CheckBox;
                IDataItemContainer container = (IDataItemContainer) chkBox.NamingContainer; 
                if(chkBox.Checked)
                {
                    PersistRowIndex(container.DataItemIndex); 
                }
                else
                {
                    RemoveRowIndex(container.DataItemIndex);
                }
            }
            gvCustomers.PageIndex = e.NewPageIndex;
            BindData(); 
        }
        private List<Int32> SelectedCustomersIndex
        {
            get
            {
                if(ViewState[SELECTED_CUSTOMERS_INDEX] == null)
                {
                    ViewState[SELECTED_CUSTOMERS_INDEX] = new List<Int32>(); 
                }
                return (List<Int32>) ViewState[SELECTED_CUSTOMERS_INDEX]; 
            }
        }
        private void RemoveRowIndex(int index)
        {
            SelectedCustomersIndex.Remove(index); 
        }
        
        private void PersistRowIndex(int index)
        {
            if(!SelectedCustomersIndex.Exists(i => i == index))
            {
                SelectedCustomersIndex.Add(index);
            }
        }
    }
}



output:


Menu From Database

Menu Database2.html
Default3.aspx
--------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" Debug="true" %>
<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
    <style type="text/css">
        .menuItem
{
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 11px;
	color: #000000;
	border: 1px solid #C8B678;
	color: #806000;
	background-color: #FFF7DD;
	padding: 4px 5px 4px 5px;
}
 .menuHover
{
	color: #EEEBE6;
	border: 1px Solid #C8B678;
	background-color: #A47E00;
	padding: 4px 5px 4px 5px;
	text-decoration: none;
}
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Menu Width="165px" ID="Menu1" StaticMenuItemStyle-CssClass="menuItem" StaticHoverStyle-CssClass="menuHover"
    DynamicHoverStyle-CssClass="menuHover" DynamicMenuItemStyle-CssClass="menuItem"
    runat="server">
    <StaticItemTemplate>
        <%# Eval("Text") %>
        <asp:Label runat="server" ID="lbItmCount">[<%#Eval("ChildItems.Count")%>]</asp:Label>
    </StaticItemTemplate>
</asp:Menu>
    </div>
    </form>
</body>
</html>
Default3.aspx.cs
------------------
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Web.Configuration;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
partial class Default3 : System.Web.UI.Page
{
    public Default3()
    {
        Load += Page_Load;
    }
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindMenu();
        }
    }
    public void BindMenu()
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        SqlDataAdapter dadCategories = new SqlDataAdapter("SELECT CatId,CatName FROM Category order by CatName", con);
        SqlDataAdapter dadSubCat = new SqlDataAdapter("SELECT SubCatId,CatId,SubCatName FROM SubCategory order by SubCatName", con);
        // Add the DataTables to the DataSet
        DataSet dsCat = new DataSet();
        using (con)
        {
            con.Open();
            dadCategories.Fill(dsCat, "Category");
            dadSubCat.Fill(dsCat, "SubCategory");
        }
        // Add a DataRelation
        dsCat.Relations.Add("Children", dsCat.Tables["Category"].Columns["CatId"], dsCat.Tables["SubCategory"].Columns["CatId"]);
        // Add the Category nodes
        int count = 0;
        foreach (DataRow categoryRow in dsCat.Tables["Category"].Rows)
        {
            MenuItem mNode = new MenuItem(Convert.ToString(categoryRow["CatName"]), "", "", "~/DetailView.aspx?CatID=" + Convert.ToString(categoryRow["CatId"]), "_parent");
            Menu1.Items.Add(mNode);
            // Get matching Sub Category
            DataRow[] subCatRows = categoryRow.GetChildRows("Children");
            foreach (DataRow row in subCatRows)
            {
                string subCatName = Convert.ToString(row["SubCatName"]);
                MenuItem subCatItems = new MenuItem(subCatName, "", "", "~/DetailView.aspx?CatID=" + Convert.ToString(row["CatId"]) + "&SubCatID=" + Convert.ToString(row["SubCatId"]), "_parent");
                Menu1.Items[count].ChildItems.Add(subCatItems);
            }
            count = count + 1;
        }
    }
    
}


 



DetailView.aspx
------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailView.aspx.cs" Inherits="DetailView" %>
<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        You have selected
        <br />
        Category ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :&nbsp;
        <asp:Label ID="lbCatID" runat="server" Text="ID Not Specified!"></asp:Label>
        <br />
        Sub Category ID :&nbsp;
        <asp:Label ID="lbSubCatID" runat="server" Text="ID Not Specified!"></asp:Label>
        <br />
        <br />
        Back to the previous page <a href="Default.aspx">Default.aspx</a></div>
    </form>
</body>
</html>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DetailView.aspx.cs" Inherits="DetailView" %>
<!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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        You have selected
        <br />
        Category ID&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; :&nbsp;
        <asp:Label ID="lbCatID" runat="server" Text="ID Not Specified!"></asp:Label>
        <br />
        Sub Category ID :&nbsp;
        <asp:Label ID="lbSubCatID" runat="server" Text="ID Not Specified!"></asp:Label>
        <br />
        <br />
        Back to the previous page <a href="Default.aspx">Default.aspx</a></div>
    </form>
</body>
</html>
DetailView.aspx.cs
---------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
public partial class DetailView : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        if ((Request.QueryString["CatId"] != null))
        {
            lbCatID.Text = Request.QueryString["CatId"];
        }
        if ((Request.QueryString["SubCatId"] != null))
        {
            lbSubCatID.Text = Request.QueryString["SubCatId"];
        }
    }
    public DetailView()
    {
        Load += Page_Load;
    }
}


output:



Menu Database3_html_m4c6debb1

Menu Control From Database

CREATE TABLE [dbo].[SAMPLECATEGORIES]
(
[id] [int] NOT NULL IDENTITY(1, 1),
[parentid] [int] NULL,
[title] [nvarchar] (255) COLLATE SQL_SwedishStd_Pref_CP1_CI_AS NOT NULL
)

-------------------------------------------------------------------------------------------

SET NUMERIC_ROUNDABORT OFF
GO
SET XACT_ABORT, ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
-- Pointer used for text / image updates. This might not be needed, but is declared here just in case
DECLARE @ptrval binary(16)

BEGIN TRANSACTION
ALTER TABLE [dbo].[SAMPLECATEGORIES] DROP CONSTRAINT [FK_SAMPLECATEGORIES_SAMPLECATEGORIES]
SET IDENTITY_INSERT [dbo].[SAMPLECATEGORIES] ON
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (1, NULL, N'Category 1')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (2, NULL, N'Category 2')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (3, NULL, N'Category 3')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (4, 1, N'Category 1.1')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (5, 1, N'Category 1.2')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (6, 2, N'Category 2.1')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (7, 2, N'Category 2.2')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (8, 2, N'Category 2.3')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (9, 7, N'Category 2.2.1')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (10, 7, N'Category 2.2.2')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (11, 10, N'Category 2.2.2.1')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (12, 6, N'Category 2.1.1')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (13, 3, N'Category 3.1')
INSERT INTO [dbo].[SAMPLECATEGORIES] ([id], [parentid], [title]) VALUES (14, 7, N'Category 2.2.3')
SET IDENTITY_INSERT [dbo].[SAMPLECATEGORIES] OFF
ALTER TABLE [dbo].[SAMPLECATEGORIES] ADD CONSTRAINT [FK_SAMPLECATEGORIES_SAMPLECATEGORIES] FOREIGN KEY ([parentid]) REFERENCES [dbo].[SAMPLECATEGORIES] ([id])
COMMIT TRANSACTION


------------------------------------------------------------------------------------------------------

/****** Script for SelectTopNRows command from SSMS  ******/
SELECT TOP 1000 [id]
      ,[parentid]
      ,[title]
  FROM [master].[dbo].[SAMPLECATEGORIES]



Menu3.aspx
------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Menu3.aspx.cs" Inherits="Menu3" %>
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
     <div>
         <asp:TreeView  
                ID="TreeView1"
                ExpandDepth="0" 
                PopulateNodesFromClient="true" 
                ShowLines="true" 
                ShowExpandCollapse="true" 
                runat="server"
                OnTreeNodePopulate="TreeView1_TreeNodePopulate"  />
    </div>
    </form>
</body>
</html>
Menu3.aspx.cs
---------------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
 
public partial class Menu3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            PopulateRootLevel();
    }
    private void PopulateRootLevel()
    {
        SqlConnection objConn = new SqlConnection(@"Data Source=truefaster\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
        SqlCommand objCommand = new SqlCommand(@"select id,title,(select count(*) FROM SampleCategories WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID IS NULL", objConn);
        SqlDataAdapter da = new SqlDataAdapter(objCommand);
        DataTable dt = new DataTable();
        da.Fill(dt);
        PopulateNodes(dt, TreeView1.Nodes);
    }
    private void PopulateSubLevel(int parentid, TreeNode parentNode)
    {
        SqlConnection objConn = new SqlConnection(@"Data Source=truefaster\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
        SqlCommand objCommand = new SqlCommand(@"select id,title,(select count(*) FROM SampleCategories WHERE parentid=sc.id) childnodecount FROM SampleCategories sc where parentID=@parentID", objConn);
        objCommand.Parameters.Add("@parentID", SqlDbType.Int).Value = parentid;
        SqlDataAdapter da = new SqlDataAdapter(objCommand);
        DataTable dt = new DataTable();
        da.Fill(dt);
        PopulateNodes(dt, parentNode.ChildNodes);
    }
    protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);
    }
    private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)
    {
        foreach (DataRow dr in dt.Rows)
        {
            TreeNode tn = new TreeNode();
            tn.Text = dr["title"].ToString();
            tn.Value = dr["id"].ToString();
            nodes.Add(tn);
            //If node has child nodes, then enable on-demand populating
            tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
        }
    }
}


output:


Menu From Database