Link to home
Start Free TrialLog in
Avatar of Tom Knowlton
Tom KnowltonFlag for United States of America

asked on

CheckBox checked state is not preserved

I have an unbound checkbox that I am programmatically adding to a GridView.

When I use the Pager control to go to a new page, the checkbox state is not preserved.

I need the checked condtion to be preserved across postbacks and when the PageIndex for the GridView changes.

I would also like to put a "check all" checkbox in the Header, but I don't know how to do that.


I'll post my source code and markup.
//MARKUP
 
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CO2SearchResults.ascx.cs"
	Inherits="UserControls_Workflow_CO2SearchResults" %>
<%@ Reference Control="~/UserControls/Workflow/PagerButton.ascx" %>
 
<script type="text/javascript">
        function RespondToPagerClick(current)
        {             
						__doPostBack(current.value,'PAGERBUTTON');              
        }    
</script>
 
<style type="text/css">
	.gridview td  
	{
		border-bottom: solid 2px black; 
		padding:10px 10px 10px 10px;
	}
	
	.pager td  
	{
		border-bottom-style:none;		
	}	
 
</style> 
 
<asp:GridView
	CssClass="gridview" 
	ID="GridViewSearchResults" 
	runat="server" 
	AllowPaging="True" 	
	GridLines="None"	
	Height="400px" 	
	OnRowDataBound="GridViewSearchResults_RowDataBound"
	EmptyDataText="No Matching Records Found" 
	AllowSorting="True" 
	AutoGenerateColumns="False">
			
		
	<PagerStyle CssClass="pager" 
		BackColor="White" 
		Wrap="False" />
	<PagerTemplate>
		<table id="table1" runat="server">
			<tr>
				<td>
					<asp:Label ID="Label2" runat="server" Text="Results:  "></asp:Label>
				</td>
				<td>
					<asp:PlaceHolder ID="phPager" runat="server"></asp:PlaceHolder>
				</td>
				<td>
					<asp:Label ID="LabelTotalWorkItems" runat="server" Text="0 items found"></asp:Label>
				</td>
			</tr>
		</table>
	</PagerTemplate>
</asp:GridView>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
//SOURCE CODE:
 
 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
 
public partial class UserControls_Workflow_CO2SearchResults : System.Web.UI.UserControl
{
	private string _workflowConnectionString = ConfigurationManager.ConnectionStrings["WORKFLOWConnection"].ConnectionString;
 
	protected ASP.PagerButton pagerBtn;
 
	protected void Page_Init( object sender, EventArgs e )
	{
		this.GridViewSearchResults.Sorting += null;
		this.GridViewSearchResults.Sorting += new GridViewSortEventHandler(this.GridViewSearchResults_Sorting);
	}
 
	protected void Page_Load( object sender, EventArgs e )
	{
		if (!Page.IsPostBack)
		{
			Cache.Remove("DataStore");
			Session["sortDir"] = SortDirection.Ascending;
		}
 
 
		string tempArgument = Request.Params.Get("__EVENTARGUMENT");
 
		if (tempArgument == "PAGERBUTTON")
		{
			string newvalue = Request.Params.Get("__EVENTTARGET");
			this.GridViewSearchResults.PageIndex = Int32.Parse(newvalue);
 
			Session["curPagerBtn"] = Request.Params.Get("__EVENTTARGET");
		}
 
		
		this.BuildGridView(LocalSelectAllWorkitemTypes());
 
		
		
	}
 
 
	public DataView LocalSelectAllWorkitemTypes()
	{
		DataSet ds = new DataSet();
 
		if (Cache["DataStore"] == null)
		{
			using (SqlConnection connection = new SqlConnection(_workflowConnectionString))
			{
				using (SqlCommand command = new SqlCommand("SelectAllWorkitemTypesTEST", connection))
				{
					command.CommandType = CommandType.StoredProcedure;
					using (SqlDataAdapter adapter = new SqlDataAdapter(command))
					{
						adapter.Fill(ds);
					}
				}
			}
						
			
			ds.Tables[0].Columns.Add("chk", typeof(CheckBoxField));
			
			DataView dv = new DataView(ds.Tables[0]);
			Cache["DataStore"] = dv;
			return dv;
		}
		else
		{
			return (DataView)Cache["DataStore"];
		}
	}
 
	private void BuildGridView(DataView dv)
	{
		this.GridViewSearchResults.AutoGenerateColumns = false;
		this.GridViewSearchResults.Columns.Clear();
		this.GridViewSearchResults.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
			
		TemplateField tf = new TemplateField();
 
		foreach (DataColumn dc in dv.Table.Columns)
		{
 
			if (dc.DataType.UnderlyingSystemType.ToString() == "System.Web.UI.WebControls.CheckBoxField")
			{
 
				tf.HeaderStyle.ForeColor = System.Drawing.Color.White;
				tf.HeaderStyle.BackColor = System.Drawing.Color.Black;
				tf.HeaderText = dc.ColumnName;
				tf.ItemStyle.VerticalAlign = VerticalAlign.Top;				
				tf.ItemTemplate = new GridViewCheckBoxColumn();				
			}
			else
			{
				BoundField bf = new BoundField();
				bf.HeaderText = dc.ColumnName;
				bf.DataField = dc.ColumnName;
				bf.HeaderStyle.ForeColor = System.Drawing.Color.White;
				bf.HeaderStyle.BackColor = System.Drawing.Color.Black;
				bf.SortExpression = dc.ColumnName;
 
				this.GridViewSearchResults.Columns.Add(bf);
			}
		}
 
		this.GridViewSearchResults.Columns.Insert(0, tf);
 
		this.GridViewSearchResults.DataSource = dv;		
		this.GridViewSearchResults.DataBind();		
	}
 
	protected void GridViewSearchResults_RowDataBound( object sender, GridViewRowEventArgs e )
	{		
		if (e.Row.RowType == DataControlRowType.Pager)
		{
			DataView dv = new DataView();
 
			dv = (DataView)Cache["DataStore"];
 
			if(dv.Table.Rows.Count > 0)
			{
				int recordcount = dv.Table.Rows.Count;
				int pagecount = recordcount / this.GridViewSearchResults.PageSize;
				
				for (int i = 1; i <= pagecount; i++)
				{
					pagerBtn = (ASP.PagerButton)LoadControl("~/UserControls/Workflow/PagerButton.ascx");
					pagerBtn.SetButtonText = i.ToString();
 
					pagerBtn.SetButtonText = i.ToString();
 
					if (Session["curPagerBtn"] != null)
					{
						if (i.ToString() == (string)Session["curPagerBtn"])
						{							
							pagerBtn.PagerButton.Enabled = false;
						//	pagerBtn.PagerButton.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Blue");
							pagerBtn.PagerButton.Style.Add(HtmlTextWriterStyle.BorderColor, "Red");
						}
						else
						{						
							pagerBtn.PagerButton.Enabled = true;
						}
					}
 
					PlaceHolder ph = (PlaceHolder)e.Row.FindControl("phPager");
 
					Label countItems = (Label)e.Row.FindControl("LabelTotalWorkItems");
 
					countItems.Text = ("(" + recordcount.ToString() + " total work items)");
					
					ph.Controls.Add(pagerBtn);
				}
			}
		}
 
		
	}
	protected void GridViewSearchResults_Sorting( object sender, GridViewSortEventArgs e )
	{
		DataView dv = new DataView();
		dv = (DataView)Cache["DataStore"];				
 
		SortDirection sd = SortDirection.Ascending;
		string newDir = "ASC";
 
		if (Session["sortDir"] != null)
		{
			sd = (SortDirection)Session["sortDir"];		
 
			if (sd == SortDirection.Ascending)
			{
				newDir = "DESC";
				Session["sortDir"] = SortDirection.Descending;
			}
			else
			{
				newDir = "ASC";
				Session["sortDir"] = SortDirection.Ascending;
			}			
		}
		else
		{			
 
			if (e.SortDirection == SortDirection.Ascending)
			{
				newDir = "ASC";				
			}
			else
			{
				newDir = "DESC";
			}
 
			Session["sortDir"] = e.SortDirection;
		}		
 
		string sortExp = e.SortExpression + " " + newDir;
		
		dv.Sort = sortExp;
			
		BuildGridView(dv);
	}
}
 
 
public class GridViewCheckBoxColumn : ITemplate
{
	public GridViewCheckBoxColumn()
	{
		//Add constructor stuff here
	}
 
	public void InstantiateIn( Control container )
	{
		CheckBox cb = new CheckBox();
		cb.DataBinding += new EventHandler(this.BindChecklistColumn);
		container.Controls.Add(cb);
	}
 
	public void BindChecklistColumn( object sender, EventArgs e )
	{
		CheckBox cb = (CheckBox)sender;
		GridViewRow container = (GridViewRow)cb.NamingContainer;
		cb.ID = Convert.ToString(DataBinder.Eval(((GridViewRow)container).DataItem, "chk"));
 
	}
}

Open in new window

checkbox.jpg
ASKER CERTIFIED SOLUTION
Avatar of Pra4444
Pra4444
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tom Knowlton

ASKER

Callbacks are not supported on TemplateField because some controls cannot update properly in a callback.  Turn callbacks off on 'GridViewSearchResults'.


Not sure what to do now.