Articles about Working with multiple checkboxes in GridView

I wanted to have multiple checkboxes in GridView . Below are a few links, that I’ve read before implemented my user control.
Checking All CheckBoxes in a GridView Using Client-Side Script and a Check All CheckBox 

 Storing and Maintaining DataGrid CheckBox Values – Selecting, Confirming & Deleting Multiple Checkbox Items In A DataGrid/GridView

Implementing ITemplate as Anonymous Method

Creating Web Server Control Templates Dynamically  by implementing  the ITemplate interface  e.g. CheckBoxTemplate ,that also INamingContainer

GridView Parent Child View with JQuery Effects 

Advertisements

Validation of viewstate MAC failed when using asp.timer to trigger UpdatePanel

I have a page with UpdatePanel and ASP:Timer, that refreshs the UpdatePanel every minute.
 
It was noticed that after new release after the first refresh any postback causes
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.”
 
I’ve searched Google and found that this error is quite common. Below there are just a few suggestions:
 
I do not consider viewStateEncryptionMode =”Never” enableViewStateMac=”false”, because it is asecurity risk.
 
Set maxPageStateFieldLength (from http://forums.asp.net/t/955145.aspx?PageIndex=9) MSDN: When the MaxPageStateFieldLength property is set to a positive number, the view state sent to the client browser is broken into multiple hidden fields, and each field’s value is less than the size specified in the MaxPageStateFieldLength property. ViewState Chunking in ASP.NET 2.0 (maxPageStateFieldLength)
 
blog Validation of viewstate MAC failed error:
It appears when using built-in databound controls such as GridView, DetailsView or FormView which utilize “DataKeyNames”.
3. It appears if you have a large page which loads slowly for any reason.
Workarounds includes
* sample code to override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form.
* mark the form as disabled and then enable it in script once the load is complete.
 
Server Side Viewstate article in .Net 1.1 -should be 2.0 version
 
Another post suggests to add
PostBackUrl=”~/samepage.aspx”
 to your Button which triggers the Postback Event:

 

Workaround from MS connect:
<meta http-equiv=”Page-Enter” content=”RevealTrans(Duration=0,Transition=0)” />
Essentially, including this tag in the header of your page disables the use of the page until it has completely downloaded to the browser.
 
Links related to debugging/viewing  ViewState
 

Create multi-row gridview Header with buttons in header

I found a few articles , that try to create multi-row gridview Header
 
All solutions suggest to create extra DataViewRow(s) of a type DataControlRowType.Header on RowDataBound event.
However on Postback DataBind usually is not called, and so RowDataBound event will not occur.
It means that the second header will not be recreated on Postback -not good.
 
Discussion GridView – trouble with double header row has a suggestion to use rowcreated event  that should be called during initial DataBind and during subsequent postback.
 
Using RowCreated event to create additional rows in header works perfectly for me.
 
Note that RowCreated event is called within parent LoadViewState event, but before LoadViewState for individual row.
So not all info could be available at that time.
Alternatively it can be tried on page_load time on PostBack when state has been loaded already as suggested in Access Dynamic GridView ItemTemplate after postback discussion.
I strongly recommend to read a great atricle: TRULY Understanding Dynamic Controls  -Parts 1-4 and avoid using dynamic controls if possible.

Remove empty lines in text using Visual Studio.

Visual Studio has ability to delete empty lines in replace operation using regular expressions.
1.Click Ctrl-H (quick replace)
2. Tick “Use Regular Expressions”
3. In Find specify ^$n
4. In Replace box delete everything.
5 Click “Replace All”
All empty lines will be deleted.

 Regular expression for empty line consist of   

Beginning of line ^

 

 

End of line $

 

Line break n

 

Note that normally in Windows an end of line  indicated by 2 characters CRLF – Carriage Return (CR, ASCII 13, r) Line Feed (LF, ASCII 10, n).

Addition from  Kenneth at 6/18/2009:
A regex to remove blank lines that are/aren’t *really* blank (i.e. they do/don’t have spaces):   ^:b*$n

Addition from   Igor  at 8/5/2011:

To remove double lines:  ^:b*n:b*n replace with:  n

 

To delete  rows with
single comma

3. In Find specify ^,$n

 

For similar requirement to remove comma at the end of lines in text, do the following steps.


1.Click Ctrl-H (quick replace)
2. Tick “Use Regular Expressions”
3.
 In Find specify ,r?n.
4. In Replace box type n

5 Click “Replace All”

 

 

Unable to set Gridview HyperLinkField Header using DataBinding

I’ve tried to set Gridview HyperLinkField Header text to some value using DataBinding

<%# Eval(“Rating”) %>

,but it caused error:

Gridview :Databinding expressions are only supported on objects that have a DataBinding event. System.Web.UI.WebControls.HyperLinkField does not have a DataBinding event. 

I had to assign Gridview HyperLinkField Header programmatically using RowDataBound event handler.

my GridViewHelper class.

Previously I’ve posted a few Helper Classes . This post describes my GridViewHelper class.

using System;

using System.Data;

using System.Configuration;

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.Diagnostics;

 

    public class GridViewHelper

    {

        //Copied from on WebFormsHelper class http://geekswithblogs.net/mnf/articles/89859.aspx

        public static int ColumnIndexBySortExpression(DataControlFieldCollection Columns, string SortExpression)

        {

            for (int i = 0; i < Columns.Count; i++)

            {

                if (Columns[i].SortExpression == SortExpression)

                {

                    return i;

                }

            }

            return -1;

        }

        public static TableCell CellBySortExpression(GridViewRow Item, string SortExpression)

        {  //actually should return DataControlFieldCell(derived from TableCell)

            GridView gridView = GetParentGridView(Item);

            int nColumn = ColumnIndexBySortExpression(gridView.Columns, SortExpression);

            if (nColumn < 0)

            {

                return null;

            }

            else

            {

                return Item.Cells[nColumn];

            }

        }

 

        public static GridView GetParentGridView(GridViewRow row)

        {

            //NOTE row.parent doesn’t return GridView

            GridView gridView = (GridView)row.NamingContainer;

            return gridView;

        }

        public static string GetFieldControlTextBySortExpression(GridViewRow Item, string SortExpression)

        {

            //can be different DataControlFields http://msdn2.microsoft.com/en-us/library/system.web.ui.webcontrols.datacontrolfield.aspx

            //the function is tested for ButtonField ,

            // for BoundField see GetColumnValueBySortExpression

            DataControlFieldCell cell = (DataControlFieldCell)CellBySortExpression(Item, SortExpression);

            string sRet = null;

            if (cell != null)

            {

                if (cell.Controls.Count > 0)

                {

                    Control cntl = cell.Controls[0];

                    if ((cntl is ITextControl))

                    {

                        sRet = ((ITextControl)cntl).Text;

                    }

                    else if (cntl is IButtonControl)

                    {    //I beleive IButtonControl should implement ITextControl interface to be consistent with others controls with Text property. 

                        sRet = ((IButtonControl)cntl).Text;

                    }

                };

            }

            return sRet;

        }

 

        public static DataControlField ColumnBySortExpression(DataControlFieldCollection Columns, string SortExpression)

        {

            DataControlField oRet = null;

            int i = ColumnIndexBySortExpression(Columns, SortExpression);

            if (i >= 0)

            {

                oRet = Columns[i];

            }

            return oRet;

        }

        //see also FieldControlTextBySortExpression

        public static string GetColumnValueBySortExpression(GridViewRow gvRow, string SortExpression)

        {

            TableCell cell = CellBySortExpression(gvRow, SortExpression);

            string sText = cell.Text;

            return sText;

        }

        /// <summary>

        /// finds CheckBox in CheckBoxField

        /// </summary>

        /// <param name=”Item”></param>

        /// <param name=”SortExpression”></param>

        /// <returns></returns>

        public static CheckBox GetCheckBoxBySortExpression(GridViewRow gvRow, string SortExpression)

        {

            //see http://forums.asp.net/p/1023839/1867775.aspx#1867775

            DataControlFieldCell cell = (DataControlFieldCell)CellBySortExpression(gvRow, SortExpression);

            CheckBox chkBox = null;

            if (cell != null)

            {

                if (cell.Controls.Count > 0)

                {

                    chkBox = cell.Controls[0] as CheckBox;

                }

            }

            return chkBox;

        }

        public static bool SetCellBySortExpressionVisible(GridViewRow gvRow, string SortExpression, bool visible)

        {

            //see http://forums.asp.net/p/1023839/1867775.aspx#1867775

            DataControlFieldCell cell = (DataControlFieldCell)CellBySortExpression(gvRow, SortExpression);

            bool bFound=false;

            //CheckBox chkBox = null;

            if (cell != null)

            {

                if (cell.Controls.Count > 0)

                {

                    Control cntl = cell.Controls[0];

                    cntl.Visible = visible;

                    bFound = true;

                };

            }

            return bFound;

        }

        public static void HyperLinkField_SetNullDisplayText(DataControlFieldCell cell, string nullDisplayText)

        {

        //TODO: implement derived from HyperLinkField class and set nullDisplayTex property

            //       TableCell cell = (TableCell) control;

            Debug.Assert((cell.ContainingField is HyperLinkField));//

 

            if (((cell.Controls.Count < 1) || !(cell.Controls[0] is HyperLink)))

            {

                throw new ApplicationException(“HyperLinkField_WrongControlType”+ cell.ToString());

            }

            HyperLink link = (HyperLink)cell.Controls[0];

            link.Visible = false;

            Label label = new Label();

            label.Text = nullDisplayText;

              label.Visible = true;

           cell.Controls.Add(label);

    }

        public static bool IsItemNormalOrAlterating(System.Web.UI.WebControls.GridViewRowEventArgs e)

        {

            bool bRet = (e.Row.RowType == DataControlRowType.DataRow);

            return bRet;

        }

        //based on http://blogs.msdn.com/mattdotson/articles/541795.aspx

        public static Table GetInnerTable(GridView gv)

        {

            if (gv.HasControls())

            {

                return (Table)gv.Controls[0];

            }

            return null;

        }

 

    }

 


my ASP.NET ListControlHelper class

Previously I’ve posted a few Helper Classes . This post describes my ListControlHelper class

   using System.Net;

    using System.IO;

    using System.Diagnostics;

    using System.Collections.Specialized;

    using System.Web.UI.WebControls;

    using System.Data;

 

    public static class ListControlHelper

    {

        public static string EmptySelectionValue = “-1”;

        //’http://blogs.msdn.com/piyush/archive/2006/10/17/how-to-bind-generic-dictionary-with-dropdown-list.aspx

        public static void ControlBinding(ListControl ctrl, Dictionary<string, string> dict)

        {

            ctrl.DataSource = dict;

            ctrl.DataValueField = “Key”;

            ctrl.DataTextField = “Value”;

        }

        //Overload for StringDictionary

        //NOTE:Do NOT use the class for Case-Sensitive data.

        public static void ControlBinding(ListControl ctrl, StringDictionary dict)

        {

            ctrl.DataSource = dict;

            ctrl.DataValueField = “Key”;

            ctrl.DataTextField = “Value”;

        }

        public static void ControlBinding(ListControl ctrl, DataTable tbl,string valueField, string textField)

        {

            ctrl.DataSource = tbl;

            ctrl.DataValueField = valueField;

            ctrl.DataTextField = textField;

        }

        public static void AddRange(ListControl pDDL, string[] asText)

        {

            foreach(string sText in asText)

            {

                pDDL.Items.Add(sText);

            }

//            return pDDL;

        }

        //Ideas from http://geekswithblogs.net/jawad/archive/2005/06/24/EnumDropDown.aspx#55344

        //, http://www.codeproject.com/useritems/enumdatabinding.asp

        //and from http://rodenbaugh.net/files/folders/18/download.aspx

        public static ListControl PopulateListControlFromEnum<TEnum>(ListControl pDDL,

                string selectedValue, EnumPopulation populateType, string emptyText, Predicate<TEnum> match)

        {

            //            pDDL.Items.Clear();

            Array values = Enum.GetValues(typeof(TEnum));

            Array names = Enum.GetNames(typeof(TEnum));

 

            if (null != emptyText)

            {

                pDDL.Items.Add(new ListItem(emptyText, “-1”));

            }

            for (int i = 0; i < values.Length; i++)

            {

                string key = “”;

                string text = “”;

                if (match != null)

                {

                    if (false == match((TEnum)values.GetValue(i)))

                    {

                        continue;

                    }

                }

 

                switch (populateType)

                {

                    case EnumPopulation.NameToName:

                        key = names.GetValue(i).ToString();

                        text = key;

                        break;

                    case EnumPopulation.ValueToName://value is numeric

                        key = Convert.ToInt32(values.GetValue(i)).ToString();

                        text = names.GetValue(i).ToString();

                        break;

                    default:

                        //case EnumPopulation.NameToDescription :

                        //case EnumPopulation.ValueToDescription :

                        Debug.Assert(false, “TODO: implement “);

                        break;

                }

                pDDL.Items.Add(new ListItem(text, key));

            }

            if (selectedValue != “”)

            {

                pDDL.SelectedValue = selectedValue;

            }

            return pDDL;

        }

        public static ListControl PopulateListControl(ListControl pDDL, string[] asText,

                string selectedValue, string emptyText)

        {

            pDDL.Items.Clear();

            AddRange(pDDL, asText);

            AddEmptyTextAndSelect(pDDL, selectedValue, emptyText);

            return pDDL;

        }

 

        public static void AddEmptyTextAndSelect(ListControl pDDL, string selectedValue, string emptyText)

        {

            if (null != emptyText)

            {

                pDDL.Items.Add(new ListItem(emptyText, “-1”));

            }

            if (selectedValue != “”)

            {

                pDDL.SelectedValue = selectedValue;

            }

        }

 

 

 

 

    //from http://geekswithblogs.net/jawad/archive/2005/06/24/EnumDropDown.aspx#55344

        //and http://www.codeproject.com/useritems/enumdatabinding.asp

        public static ListControl PopulateListControlFromEnum<TEnum>(ListControl pDDL,

            string selectedValue, EnumPopulation populateType, string emptyText)

        {

            return PopulateListControlFromEnum<TEnum>( pDDL, selectedValue,  populateType,  emptyText,null);

//            pDDL.Items.Clear();

            //Array values = Enum.GetValues(enumType);

            //Array names = Enum.GetNames(enumType);

 

            //if (null!=emptyText)

            //{

            //    pDDL.Items.Add(new ListItem(emptyText, “-1”)) ;

            //}

            //for(int i=0;i < values.Length;i++)

            //{

            //    string key =””;

            //    string text=””;

            //    switch(populateType)

            //    {

            //        case EnumPopulation.NameToName:

            //           key = names.GetValue(i).ToString();

            //           text =key;

            //            break;

            //        case EnumPopulation.ValueToName: //value is numeric

            //           key =Convert.ToInt32(values.GetValue(i)).ToString();

            //           text = names.GetValue(i).ToString();

            //            break;

            //        default:

            //        //case EnumPopulation.NameToDescription :

            //            //case EnumPopulation.ValueToDescription :

            //            Debug.Assert(false,”TODO: implement “);

            //            break;

            //    }

            //    pDDL.Items.Add(new ListItem(text, key));

            //}

            //if (selectedValue != “”)

            //{

            //    pDDL.SelectedValue =  selectedValue;

            //}

            //return pDDL;

        }

        public static int GetSelectedEnumValue<TEnum>(ListControl pDDL) where TEnum : struct

        {

            string selectedValue = pDDL.SelectedValue;

            if (selectedValue != “”)

            {

                TEnum enRet = EnumHelper.Parse<TEnum>(selectedValue);

                return Convert.ToInt32(enRet);//(int)

            }

            return -1;

 

        }

        public static ListItem ReplaceListItem(ListControl pDDL, string originalEmptyValue, string emptyText, string newEmptyValue)

        {

            ListItem li=pDDL.Items.FindByValue(originalEmptyValue);

            if(li!=null)

            {

                if (null != emptyText)

                {

                    li.Text = emptyText;

                }

                if (null != newEmptyValue)

                {

                    li.Value  = newEmptyValue;

                }

            }

            return li;

        }

        public static bool IsItemSelected(DropDownList ddlMonth)

        {

 

            if ((ddlMonth == null) || (ddlMonth.SelectedItem == null))

            {

                return false;

            }

            return true;

        }

 

        public enum EnumPopulation

        {

            ValueToName,

            NameToName,

            NameToDescription,

            ValueToDescription

        }

 

        }// class ListControlHelper