Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
263
Templated Column Programatically
posted

Hi all,

 

I have added templeted textbox column from code behind to my webgrid...

However if I do a paging or sorting I loose the text box and the column comes up like a regular column..

Any ideas on how to resolve this issue?

Thanks for your help..

 

Joel

Parents
  • 2197
    posted

    Hello.

    In order to properly create templated columns in code, you need to create a class that implements the ITemplate interface and then handle one method; namely the InstantiateIn method. This method is where you will add the controls to the CellItem. You also need to set the CellTemplate property on the column object to a new instance of your class that implements ITemplate. Thirdly, you need to handle the grids server side TemplatedColumnRestored event. Here is some code to demonstrate this. First, we add the templated column in InitializeLayout:

     TemplatedColumn tc = new TemplatedColumn(true);
     tc.Key = "ImageButton";
     tc.Header.Caption = "Image Button";
     e.Layout.Bands[0].Columns.Add(tc);

     //Set the columns template to a new instance of the PlaceHolderTemplate class.
     tc.CellTemplate = new PlaceHolderTemplate();

    Here is the PlaceHolderTemplate class. All I am doing is placing a standard ImageButton into the cell template, but the process is the same for other controls:

    public class PlaceHolderTemplate : ITemplate
        {
            #region ITemplate Members

            void ITemplate.InstantiateIn(Control container)
            {
                CellItem ci = (CellItem)container;
                //Create a new instance of the image button, assign alternaten text, and add it to
                //the cell template.
                ImageButton ib = new ImageButton();
                ib.EnableViewState = true;
                ci.Controls.Add(ib);
            }

            #endregion
        }

     Here is the grids TemplatedColumnRestored event where you need to check the contents of the cell template on each postback:

     if (((TemplatedColumn)e.Column).CellTemplate == null)
     {
         ((TemplatedColumn)e.Column).CellTemplate = new PlaceHolderTemplate();
     }

     Following these steps will ensure that your programmatically created templated columns will work and that the controls will be created on every postback.

Reply Children