Click here to Skip to main content
Click here to Skip to main content

Telerik RadGrid Helper Class for ASP.NET

, 3 Sep 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Telerik RadGrid Helper Class for ASP.NET

Editorial Note

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Introduction

In this article I will explain about how to create a Helper Class for Telerik Radgrid in ASP.NET. In one of my web project I ‘am using Telerik grid. When i start my project I was looking for a Helper Class for RadGrid at Telerik Site and used Google for get one Helper Class. But i couldn’t found any helper class for Telerik Radgrid. So I plan to create a Helper Class for Telerik Rad Grid. As a result I have created a helper class for Telerik Radgrid. I want to share my helper class with others so that they can use my class in there project and make a code simple and easy.

WHY WE NEED HELPER CLASS:

  • Helper Class will make our code part Simple and Standard.
  • No more need of Radgrid design in ASPX page. Everything can be done in CS part.
  • One Time Design in Class can be used for the whole project.
  • This will be useful if we change design only in Class File and no need to redesign in each page.

Note: In my Sample I have used Telerik ASP.NET Version 2013.3.1114.40.I have removed my Telerik dll from the zip file. If you want to run my sample program you need to add your Telerik dll to my project. You can download a trial version of Telerik or you can purchase the full version from Telerik Website.

In this sample project I have created sample ASP.net program with my helper Class. In my Sample program i have also explain about basic JavaScript event of radgrid and Check box check event of column header. Here is a sample of showing the JavaScript message from the grid Search Box column click event.

Using the Code

First we can start with the helper class and then we can see how to use the helper class in ASP.Net Page. In my helper class I have the fallowing function to make the design and bind simple.

  • Layout
  • LayoutPage
  • Client Settings
  • keyboardNavigation
  • ClientEvents
  • ExporttoExcel
  • DataBind
  • GridMastertableSetting
  • ColumnGroups
  • BoundColumn
  • ImageColumn
  • Template Column
  • Image Coulmn
  • Button Column
  • TemplateColumn Class
  • Bind Controls

We can see few important functions of the class and then i will paste my full class Code here.

Layout: This method will be setting the Skin, Height and width of the grid and etc. The width can be set as percentage or as value, if the width type is false then use as the vale or if its true then use as a percentage to display the grid.

 #region Layout
    public static void Layouts(RadGrid grid, int height, int width, Boolean widthtype, Boolean multirowselect, Boolean allowsorting, Boolean showstatusbar, Boolean allowfilteringbycolumns, Boolean showgrouppannel, Boolean ShowHeader, Boolean ShowFooter)
    {
        grid.AutoGenerateColumns = false; // set the auto genrated columns as false
        grid.Skin = "Office2007";// set the Skin
        grid.AllowMultiRowSelection = multirowselect;//set the multirow selection as true or false     
        grid.AllowSorting = allowsorting; // Set Sorting for a grid
        // set grid lines as none
        grid.GridLines = GridLines.Both;
        grid.ShowStatusBar = showstatusbar; // set true or false to display the status bar
        grid.AllowFilteringByColumn = allowfilteringbycolumns; //Set the Filtering for a individual columns
       
        grid.Height = height; //Set the height of the grid  in % or in pixcel
        if (width > 0)
        {
            if (widthtype == false)
            {
                grid.Width = width; // set the Width of the grid  in % or in pixcel
            }
            else
            {
                grid.Width = Unit.Percentage(width);
            }
        }       
        grid.ShowGroupPanel = showgrouppannel;//show group panel for header
        grid.ShowHeader = ShowHeader; // show header of the grid true or false
        grid.ShowFooter = ShowFooter; // show header of the grid true or false
    }

    #endregion

Client Events: This method can be used to set all the client events of radgrid.

 #region ClientEvents
    public static void ClientEvents(RadGrid grid, clientEventType clienteventtype, String clientfunctionname)
    {
        switch (clienteventtype.ToString())
        {
            case "gridCreated":
                grid.ClientSettings.ClientEvents.OnGridCreated = clientfunctionname;//"GetGridObject";
                break;
            case "rowClicked":
                grid.ClientSettings.ClientEvents.OnRowClick = clientfunctionname;
                break;
            case "rowDblClick":
                grid.ClientSettings.ClientEvents.OnRowDblClick = clientfunctionname;
                break;
            case "ColumnClick":
                grid.ClientSettings.ClientEvents.OnColumnClick = clientfunctionname;
                break;
            case "OnRowSelected":
                grid.ClientSettings.ClientEvents.OnRowSelected = clientfunctionname;
                break;
            case "OnKeyPress":
                grid.ClientSettings.ClientEvents.OnKeyPress = clientfunctionname;
                break;

        }


    }
    #endregion

Bound Column: Bound column method can be called if the grid column type needs to be set as Bound Column. User can pass all the parameter from the “cs” page to this class to use the bound column.

 //Bound column is used to display the data 
    #region BoundColumn
    public static void BoundColumn(RadGrid grid, String HeaderText, String datafield, String UniqueName, String groupName, HorizontalAlign Alignment, int Width, String Aggregate, Boolean AllowFiltering, Boolean colDisplay, VerticalAlign verticalAlignment, HorizontalAlign itemAlignment)
    {
        GridBoundColumn boundColumn;
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = datafield;
        boundColumn.HeaderText = HeaderText;
        boundColumn.UniqueName = UniqueName;
        if (groupName != String.Empty)
        {
            boundColumn.ColumnGroupName = groupName;
        }

        boundColumn.HeaderStyle.HorizontalAlign = Alignment;
        boundColumn.HeaderStyle.VerticalAlign = verticalAlignment;
        boundColumn.ItemStyle.HorizontalAlign = itemAlignment;
        boundColumn.HeaderStyle.Width = Width;
        boundColumn.Aggregate = GridAggregateFunction.None;
        boundColumn.Display = colDisplay;
        boundColumn.AllowFiltering = AllowFiltering;
        boundColumn.DataFormatString = "{0:n0}";
        if (Aggregate != String.Empty)
        {
            // boundColumn.FooterText = Footertext;
          
            switch (Aggregate)
            {
                case "Sum":
                    boundColumn.Aggregate = GridAggregateFunction.Sum;
                    boundColumn.FooterAggregateFormatString = " {0:n0}";
                    boundColumn.FooterStyle.Font.Bold = true;
                    break;
                case "Avg":
                    boundColumn.Aggregate = GridAggregateFunction.Avg;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
                case "Count":
                    boundColumn.Aggregate = GridAggregateFunction.Count;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0}";
                    break;
                case "Max":
                    boundColumn.Aggregate = GridAggregateFunction.Max;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
                case "Min":
                    boundColumn.Aggregate = GridAggregateFunction.Min;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
            }
            //boundColumn.FooterText = Footertext;
            //  boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";

        }

        grid.MasterTableView.Columns.Add(boundColumn);
    }
    #endregion

helperClass Full Source Code :  Here is the full source code of the Telerik Grid helper class. I have created all the necessary methods which need to be used. if user need any more they can add those functions as well here in this class and use in your projects. In this helper class we can see a "MyTemplate" Class, which will be used to bind the template Column and Button Columns to bind the controls to the grid.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Telerik.Web.UI;
using System.Drawing;
using System.Web.UI.WebControls;
using System.Web.UI;

// Author : Shanu // Create date : 2019-09-04 // Description : telerikGridHelper // Latest // Modifier : Shanu // Modify date : 2019-09-04 // 
public class TelerikGridHelper
{
	public TelerikGridHelper()
	{	}
    //Set all the telerik Grid layout
    #region Layout
    public static void Layouts(RadGrid grid, int height, int width, Boolean widthtype, Boolean multirowselect, Boolean allowsorting, Boolean showstatusbar, Boolean allowfilteringbycolumns, Boolean showgrouppannel, Boolean ShowHeader, Boolean ShowFooter)
    {
        grid.AutoGenerateColumns = false; // set the auto genrated columns as false
        grid.Skin = "Office2007";// set the Skin
        grid.AllowMultiRowSelection = multirowselect;//set the multirow selection as true or false     
        grid.AllowSorting = allowsorting; // Set Sorting for a grid
        // set grid lines as none
        grid.GridLines = GridLines.Both;
        grid.ShowStatusBar = showstatusbar; // set true or false to display the status bar
        grid.AllowFilteringByColumn = allowfilteringbycolumns; //Set the Filtering for a individual columns
       
        grid.Height = height; //Set the height of the grid  in % or in pixcel
        if (width > 0)
        {
            if (widthtype == false)
            {
                grid.Width = width; // set the Width of the grid  in % or in pixcel
            }
            else
            {
                grid.Width = Unit.Percentage(width);
            }
        }       
        grid.ShowGroupPanel = showgrouppannel;//show group panel for header
        grid.ShowHeader = ShowHeader; // show header of the grid true or false
        grid.ShowFooter = ShowFooter; // show header of the grid true or false
    }

    #endregion

    //Set all the telerik Grid Page
    #region LayoutPage
    public static void LayoutPage(RadGrid grid, int pagesize, Boolean allowpaging)
    {
        grid.PageSize = pagesize;//Set the Grid Page default page size
        grid.AllowPaging = allowpaging;//Set Paging for a grid as true or false
        grid.PagerStyle.PageSizeControlType = PagerDropDownControlType.None; 

        grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
       

    }
    #endregion

    //Client Settings like columns reorder, scrolling and resize
    #region ClientSetting
    public static void ClientSetting(RadGrid grid, Boolean ColumnReorder, Boolean ReorderColumnsOnClient, Boolean AllowColumnResize, Boolean EnableRealTimeResize, Boolean AllowRowSelect, Boolean EnableRowHoverStyle, int FrozenColumnsCount)
    {
        grid.ClientSettings.AllowColumnsReorder = ColumnReorder;
        grid.ClientSettings.ReorderColumnsOnClient = ReorderColumnsOnClient;
        grid.ClientSettings.EnableRowHoverStyle = EnableRowHoverStyle;
        grid.ClientSettings.Scrolling.AllowScroll = true;
        grid.ClientSettings.Scrolling.SaveScrollPosition = true;
        grid.ClientSettings.Scrolling.UseStaticHeaders = true;
        grid.ClientSettings.Scrolling.ScrollHeight = 125;
        grid.ClientSettings.Scrolling.ScrollBarWidth = 100;
        grid.ClientSettings.Scrolling.FrozenColumnsCount = FrozenColumnsCount;
        grid.ClientSettings.Resizing.EnableRealTimeResize = EnableRealTimeResize;
        grid.ClientSettings.Resizing.AllowColumnResize = AllowColumnResize;
        grid.ClientSettings.Selecting.AllowRowSelect = AllowRowSelect;

        //grid.ClientSettings.Scrolling.EnableVirtualScrollPaging = true;        

    }
    #endregion

    //Client Settings ForKeyboardNavigation
    #region ClientSetting
    public static void ClientSettingKEYBOARDNavi(RadGrid grid, Boolean AllowKeyboardNavigation, Boolean EnableKeyboardShortcuts, Boolean AllowActiveRowCycle)
    {
        
        grid.ClientSettings.Selecting.CellSelectionMode = GridCellSelectionMode.MultiCell;
        grid.ClientSettings.Selecting.EnableDragToSelectRows = false;
        grid.ClientSettings.AllowKeyboardNavigation = AllowKeyboardNavigation;
        grid.ClientSettings.KeyboardNavigationSettings.EnableKeyboardShortcuts = EnableKeyboardShortcuts;
        grid.ClientSettings.KeyboardNavigationSettings.AllowActiveRowCycle = AllowActiveRowCycle;

        //grid.ClientSettings.Resizing.AllowColumnResize = true;
        //grid.ClientSettings.Resizing.EnableRealTimeResize = true;

    }
    #endregion

    //Client Events .this function used to decalre the client side events
    #region ClientEvents
    public static void ClientEvents(RadGrid grid, clientEventType clienteventtype, String clientfunctionname)
    {
        switch (clienteventtype.ToString())
        {
            case "gridCreated":
                grid.ClientSettings.ClientEvents.OnGridCreated = clientfunctionname;//"GetGridObject";
                break;
            case "rowClicked":
                grid.ClientSettings.ClientEvents.OnRowClick = clientfunctionname;
                break;
            case "rowDblClick":
                grid.ClientSettings.ClientEvents.OnRowDblClick = clientfunctionname;
                break;
            case "ColumnClick":
                grid.ClientSettings.ClientEvents.OnColumnClick = clientfunctionname;
                break;
            case "OnRowSelected":
                grid.ClientSettings.ClientEvents.OnRowSelected = clientfunctionname;
                break;
            case "OnKeyPress":
                grid.ClientSettings.ClientEvents.OnKeyPress = clientfunctionname;
                break;

        }


    }
    #endregion

    #region ExporttoExcel
    public static void ExporttoExcel(RadGrid grid, Boolean ExportOnlyData, Boolean IgnorePaging, Boolean OpenInNewWindow, Boolean UseItemStyles)
    {


        grid.ExportSettings.ExportOnlyData = ExportOnlyData;
        grid.ExportSettings.IgnorePaging = IgnorePaging;
        grid.ExportSettings.OpenInNewWindow = OpenInNewWindow;
        grid.ExportSettings.UseItemStyles = UseItemStyles;

        grid.MasterTableView.ExportToExcel();
    }
    #endregion
    // bind the Datatable to  grid
    #region DataBind
    public static void DataBinds(RadGrid grid, DataTable dataTable, Boolean needdatasource)
    {


        grid.DataSource = dataTable;
        if (!needdatasource)
        {
            grid.DataBind();
        }
    }
    public static void DataBinds(RadGrid grid, DataSet dataSet, Boolean needdatasource)
    {
        DataBinds(grid, dataSet.Tables[0], needdatasource);
    }
    #endregion

    //In this Mastertbaleview we define the datakey for the grid
    #region GridMasterTableSetting
    public static void Mastertableview(RadGrid grid, String[] keyvalue, Boolean allowfilteringbycolumn)
    {
        if (keyvalue[0] != String.Empty)
        {
            grid.MasterTableView.DataKeyNames = keyvalue; // set the grid Datakeyname use ,(comma) for more then one key
            grid.MasterTableView.ClientDataKeyNames = keyvalue; //set the Client Datakey names
        }
        // grid.MasterTableView.TableLayout = "Auto";
        grid.MasterTableView.EnableHeaderContextMenu = true;
        grid.MasterTableView.AllowFilteringByColumn = allowfilteringbycolumn;
        grid.MasterTableView.Font.Size = 9;
        grid.MasterTableView.TableLayout = GridTableLayout.Fixed;


        //grid.MasterTableView.ExpandCollapseColumn.Visible = false;
        //grid.MasterTableView.ExpandCollapseColumn.Visible = false;
        //grid.MasterTableView.ExpandCollapseColumn.Display = false;
      //  grid.MasterTableView.EnableGroupsExpandAll = false;
       
        grid.MasterTableView.ShowGroupFooter = true;
        grid.MasterTableView.ShowFooter = true;
       
    }
    #endregion

    //here we define each column type and value and text
    #region gridColumnType

    //To set the Grid header column groups
    #region ColumnGroups
    public static void ColumnGroups(RadGrid grid, String groupHeaderText, String groupName, String ParentgroupName, HorizontalAlign Alignment, int Width)
    {
        if (groupHeaderText == String.Empty)
        {
            return;
        }
        GridColumnGroup columnGroup = new GridColumnGroup();
        columnGroup.HeaderText = groupHeaderText;
        columnGroup.Name = groupName;
        columnGroup.HeaderStyle.HorizontalAlign = Alignment;
        columnGroup.HeaderStyle.Width = Width;
        if (ParentgroupName != String.Empty)
        {
            columnGroup.ParentGroupName = ParentgroupName;
        }
        grid.MasterTableView.ColumnGroups.Add(columnGroup);

    }
    #endregion


    //Bound column is used to display the data 
    #region BoundColumn
    public static void BoundColumn(RadGrid grid, String HeaderText, String datafield, String UniqueName, String groupName, HorizontalAlign Alignment, int Width, String Aggregate, Boolean AllowFiltering, Boolean colDisplay, VerticalAlign verticalAlignment, HorizontalAlign itemAlignment)
    {
        GridBoundColumn boundColumn;
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = datafield;
        boundColumn.HeaderText = HeaderText;
        boundColumn.UniqueName = UniqueName;
        if (groupName != String.Empty)
        {
            boundColumn.ColumnGroupName = groupName;
        }

        boundColumn.HeaderStyle.HorizontalAlign = Alignment;
        boundColumn.HeaderStyle.VerticalAlign = verticalAlignment;
        boundColumn.ItemStyle.HorizontalAlign = itemAlignment;
        boundColumn.HeaderStyle.Width = Width;
        boundColumn.Aggregate = GridAggregateFunction.None;
        boundColumn.Display = colDisplay;
        boundColumn.AllowFiltering = AllowFiltering;
        boundColumn.DataFormatString = "{0:n0}";
        if (Aggregate != String.Empty)
        {
            // boundColumn.FooterText = Footertext;
          
            switch (Aggregate)
            {
                case "Sum":
                    boundColumn.Aggregate = GridAggregateFunction.Sum;
                    boundColumn.FooterAggregateFormatString = " {0:n0}";
                    boundColumn.FooterStyle.Font.Bold = true;
                    break;
                case "Avg":
                    boundColumn.Aggregate = GridAggregateFunction.Avg;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
                case "Count":
                    boundColumn.Aggregate = GridAggregateFunction.Count;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0}";
                    break;
                case "Max":
                    boundColumn.Aggregate = GridAggregateFunction.Max;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
                case "Min":
                    boundColumn.Aggregate = GridAggregateFunction.Min;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
            }
            //boundColumn.FooterText = Footertext;
            //  boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";

        }

        grid.MasterTableView.Columns.Add(boundColumn);
    }
    #endregion


    //Bound column is used to display the data 
    #region BoundColumn
    public static void BoundColumnnoFormat(RadGrid grid, String HeaderText, String datafield, String UniqueName, String groupName, HorizontalAlign Alignment, int Width, String Aggregate,String FooterText, Boolean AllowFiltering, Boolean colDisplay, VerticalAlign verticalAlignment, HorizontalAlign itemAlignment)
    {
        GridBoundColumn boundColumn;
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = datafield;
        boundColumn.HeaderText = HeaderText;
        boundColumn.UniqueName = UniqueName;
        if (groupName != String.Empty)
        {
            boundColumn.ColumnGroupName = groupName;
        }

        boundColumn.HeaderStyle.HorizontalAlign = Alignment;
        boundColumn.HeaderStyle.VerticalAlign = verticalAlignment;
        boundColumn.ItemStyle.HorizontalAlign = itemAlignment;
        boundColumn.HeaderStyle.Width = Width;
        boundColumn.Aggregate = GridAggregateFunction.None;
        boundColumn.Display = colDisplay;
        boundColumn.AllowFiltering = AllowFiltering;
      //  boundColumn.DataFormatString = "{0:n0}";
        if (Aggregate != String.Empty)
        {
            // boundColumn.FooterText = Footertext;

            switch (Aggregate)
            {
                case "Sum":
                    boundColumn.Aggregate = GridAggregateFunction.Sum;
                    boundColumn.FooterAggregateFormatString = FooterText + "{0:n}";
                    boundColumn.FooterStyle.Font.Bold = true;
                   // boundColumn.FooterText = "합계";
                    break;
                case "Avg":
                    boundColumn.Aggregate = GridAggregateFunction.Avg;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
                case "Count":
                    boundColumn.Aggregate = GridAggregateFunction.Count;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0}";
                    break;
                case "Max":
                    boundColumn.Aggregate = GridAggregateFunction.Max;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
                case "Min":
                    boundColumn.Aggregate = GridAggregateFunction.Min;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    break;
                case "None":
                  boundColumn.Aggregate = GridAggregateFunction.None;
                    boundColumn.FooterAggregateFormatString = FooterText ;
                    boundColumn.FooterText = FooterText;
                    boundColumn.FooterStyle.Font.Bold = true;
                    break;
                // boundColumn.FooterText = "합계";
            }
            //boundColumn.FooterText = Footertext;
            //  boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";

        }

        grid.MasterTableView.Columns.Add(boundColumn);
    }
    #endregion

    //Image column is used to add the image to the column
    #region ImageColumn
    public static void ImageColumn(RadGrid grid, String HeaderText, String[] datafield, String imageURL, String AlternateText, String groupName, ImageAlign imgAlign, int ImageHeight, int ImageWidth, int ColWidth)
    {
        GridImageColumn imageColumn;
        imageColumn = new GridImageColumn();
        imageColumn.HeaderText = HeaderText;
        imageColumn.DataImageUrlFields = datafield;
        if (groupName != String.Empty)
        {
            imageColumn.ColumnGroupName = groupName;
        }
        imageColumn.DataImageUrlFormatString = imageURL;
        imageColumn.AlternateText = AlternateText;
        imageColumn.HeaderStyle.Width = ColWidth;
        imageColumn.ImageAlign = imgAlign;
        imageColumn.ItemStyle.Width = ColWidth;
        imageColumn.AllowFiltering = false;
        if (ImageHeight > 0)
        {
            imageColumn.ImageHeight = ImageHeight;
        }
        if (ImageWidth > 0)
        {
            imageColumn.ImageWidth = ImageWidth;
        }

        grid.MasterTableView.Columns.Add(imageColumn);
    }
    #endregion

    //Template Column In this column we can add Textbox,Lable,Check Box,Dropdown box,LinkButton,button,Image Button,numeric textbox and etc
    #region Templatecolumn
    //public static void Templatecolumn(RadGrid grid, String HeaderText, String datafield, String UniqueName, String groupName, HorizontalAlign Alignment, int Width, String Aggregate, String Footertext, Boolean AllowFiltering,String Columntype)
    public static void Templatecolumn(RadGrid grid, String HeaderText, String datafield, String UniqueName, String groupName, HorizontalAlign Alignment, int Width, Boolean AllowFiltering, TelerikControlType Columntype, String contolID, String CommandName, Boolean chklableVisible, HorizontalAlign ItemAlignment, Boolean ColumnDisplay)
    {
        if (Width <= 10)
        {
            Width = 20;
        }
        GridTemplateColumn templateColumn;
        templateColumn = new GridTemplateColumn();
        templateColumn.ItemTemplate = new MyTemplate(datafield, Columntype.ToString(), Width - 2, contolID, CommandName, chklableVisible);
        templateColumn.HeaderText = HeaderText;
        templateColumn.DataField = "datafield";
        templateColumn.UniqueName = UniqueName;
        templateColumn.Display = ColumnDisplay;
        if (groupName != String.Empty)
        {
            templateColumn.ColumnGroupName = groupName;
        }
        templateColumn.HeaderStyle.HorizontalAlign = Alignment;
        templateColumn.ItemStyle.HorizontalAlign = ItemAlignment;
        templateColumn.HeaderStyle.Width = Width;
       


        templateColumn.Aggregate = GridAggregateFunction.None;

        templateColumn.AllowFiltering = AllowFiltering;

        //if (Aggregate != String.Empty)
        //{
        //    templateColumn.FooterAggregateFormatString = templateColumn.Aggregate.ToString() + ": {0:n}";
        //    switch (Aggregate)
        //    {
        //        case "Sum":
        //            templateColumn.Aggregate = GridAggregateFunction.Sum;
        //            break;
        //        case "Avg":
        //            templateColumn.Aggregate = GridAggregateFunction.Avg;
        //            break;
        //        case "Count":
        //            templateColumn.Aggregate = GridAggregateFunction.Count;
        //            templateColumn.FooterAggregateFormatString = templateColumn.Aggregate.ToString() + ": {0}";
        //            break;
        //        case "Max":
        //            templateColumn.Aggregate = GridAggregateFunction.Max;
        //            break;
        //        case "Min":
        //            templateColumn.Aggregate = GridAggregateFunction.Min;
        //            break;
        //    }
        //}
        //templateColumn.FooterText = Footertext;


        grid.MasterTableView.Columns.Add(templateColumn);
    }
    #endregion

    //Add a Button Column to a teleik grid
    #region ButtonColumn
    public static void ButtonColumn(RadGrid grid, String HeaderText, String UniqueName, String groupName, HorizontalAlign Alignment, int Width, String buttonText, GridButtonColumnType buttontype, String commandName, String imageURL, Boolean colDisplay)
    {
        GridButtonColumn buttonColum = new GridButtonColumn();
        buttonColum.HeaderText = HeaderText;
        buttonColum.UniqueName = UniqueName;
        if (groupName != String.Empty)
        {
            buttonColum.ColumnGroupName = groupName;
        }

        buttonColum.HeaderStyle.HorizontalAlign = Alignment;
        buttonColum.HeaderStyle.Width = Width;
        buttonColum.Display = colDisplay;
        buttonColum.Text = buttonText;
        buttonColum.ButtonType = buttontype;
        buttonColum.CommandName = commandName;
        buttonColum.ImageUrl = imageURL;


        grid.MasterTableView.Columns.Add(buttonColum);
    }
    #endregion

    #endregion

    # region TemplateColumnClass
    public class MyTemplate : ITemplate
    {
        #region Variables

        // controls
        protected RequiredFieldValidator validatorTextBox;
        protected TextBox textBox;
        protected CheckBox boolValue;
        protected LinkButton linkbutton;
        protected DropDownList combobox;
        protected RadTextBox searchTextBox;
        protected RadTextBox searchTextBoxNOBRDR;
        protected RadNumericTextBox numericTextBox;
        protected RadDatePicker radDate;
        protected Label label;
        protected System.Web.UI.WebControls.Image searchImg;

        //loacl variable
        private String colname;
        private String Columntype;
        private int cntrlwidth;
        private String cntrlId;
        private String CmdName;
        private Boolean chkLblVisible;
        # endregion

        #region bindControls

        public MyTemplate(string cName, String Ctype, int controlWidth, String ControlID, String CommandName, Boolean chklableVisible)
        {
            colname = cName;
            Columntype = Ctype;
            cntrlwidth = controlWidth;
            cntrlId = ControlID;
            CmdName = CommandName;
            chkLblVisible = chklableVisible;
        }

        public void InstantiateIn(System.Web.UI.Control container)
        {
            switch (Columntype)
            {
                case "TextBox":

                    textBox = new TextBox();
                    textBox.ID = cntrlId;
                    textBox.Width = cntrlwidth-6;
                    textBox.BorderWidth = 0;
                    textBox.DataBinding += new EventHandler(textBox_DataBinding);
                    //validatorTextBox = new RequiredFieldValidator();
                    //validatorTextBox.ControlToValidate = cntrlId;
                    //validatorTextBox.ErrorMessage = "*";

                    container.Controls.Add(textBox);
                    ///container.Controls.Add(validatorTextBox);
                    break;

                case "SearchTextBox":

                    searchTextBox = new RadTextBox();
                    searchTextBox.ID = cntrlId;
                    searchTextBox.Width = cntrlwidth - 20;
                    searchTextBox.ShowButton = false;
                    searchTextBox.DataBinding += new EventHandler(searchtextBox_DataBinding);
                    searchTextBox.BorderWidth = 0;

                    searchImg = new System.Web.UI.WebControls.Image();
                    searchImg.ID = "img" + cntrlId;
                    searchImg.ImageUrl = "~/Images/icFind.gif";
                    searchImg.Attributes["style"] = "cursor:hand";

                    container.Controls.Add(searchTextBox);
                    container.Controls.Add(searchImg);
                    //container.Controls.Add(validatorTextBox);
                    break;
                case "SearchTextBoxNOBORDER":

                    searchTextBoxNOBRDR = new RadTextBox();
                    searchTextBoxNOBRDR.ID = cntrlId;
                    searchTextBoxNOBRDR.Width = cntrlwidth - 4;
                    searchTextBoxNOBRDR.ShowButton = false;
                    searchTextBoxNOBRDR.BorderWidth = 0;
                    searchTextBoxNOBRDR.ReadOnly = true;
                    searchTextBoxNOBRDR.DataBinding += new EventHandler(searchtextBoxNoBORDER_DataBinding);
                    //validatorTextBox = new RequiredFieldValidator();
                    //validatorTextBox.ControlToValidate = cntrlId;
                    //validatorTextBox.ErrorMessage = "*";
                    container.Controls.Add(searchTextBoxNOBRDR);
                    //container.Controls.Add(validatorTextBox);
                    break;
                case "NumericTextBox":

                    numericTextBox = new RadNumericTextBox();
                    numericTextBox.ID = cntrlId;
                    numericTextBox.Width = cntrlwidth-6;
                    numericTextBox.AutoCompleteType = AutoCompleteType.None;
                    numericTextBox.Type = NumericType.Number;
                    numericTextBox.ShowSpinButtons = false;
                    numericTextBox.AllowOutOfRangeAutoCorrect = false;
                    numericTextBox.BorderWidth = 0;
                    // numericTextBox.InvalidStyle.Font = false;
                    numericTextBox.NumberFormat.AllowRounding = false;
                    numericTextBox.NumberFormat.DecimalDigits = 3;
                    numericTextBox.NumberFormat.KeepNotRoundedValue = true;

                    numericTextBox.DataBinding += new EventHandler(numerictextBox_DataBinding);

                    container.Controls.Add(numericTextBox);

                    break;

                case "LinkButton":

                    linkbutton = new LinkButton();
                    linkbutton.ID = cntrlId;
                    linkbutton.Width = cntrlwidth-6;
                    linkbutton.CommandName = CmdName;
                    linkbutton.DataBinding += new EventHandler(linkbutton_DataBinding);
                    container.Controls.Add(linkbutton);
                    break;

                case "CheckBox":


                    boolValue = new CheckBox();
                    boolValue.ID = cntrlId;
                    boolValue.DataBinding += new EventHandler(boolValue_DataBinding);

                    if (chkLblVisible == true)
                    {
                        label = new Label();
                        label.ID = "lbl_" + cntrlId;
                        label.Width = cntrlwidth-6;
                       
                        label.DataBinding += new EventHandler(label_DataBinding);

                        container.Controls.Add(label);
                    }

                    container.Controls.Add(boolValue);
                    break;

                case "ComboBox":
                    combobox = new DropDownList();
                    combobox.ID = cntrlId;
                    combobox.Width = cntrlwidth-8;
                    combobox.AutoPostBack = false;
                    container.Controls.Add(combobox);
                    break;

                case "RadDatePicker":

                    radDate = new RadDatePicker();
                    radDate.ID = cntrlId;
                    radDate.Width = cntrlwidth - 6;
                    radDate.EnableScreenBoundaryDetection = false;
                    radDate.DateInput.DateFormat = "yyyy-MM-dd";

                    radDate.DataBinding += new EventHandler(radDate_DataBinding);
                    container.Controls.Add(radDate);
                    break;

                case "Label":

                    label = new Label();
                    label.ID = cntrlId;
                    label.Width = cntrlwidth-6;
                    label.DataBinding += new EventHandler(label_DataBinding);

                    container.Controls.Add(label);
                    break;
            }
        }
        void boolValue_DataBinding(object sender, EventArgs e)
        {
            //  CheckBox cBox = (CheckBox)sender;
            //  GridDataItem container = (GridDataItem)cBox.NamingContainer;
            ////  cBox.Checked = (bool)((DataRowView)container.DataItem)["id"];
        }
        public void label_DataBinding(object sender, EventArgs e)
        {
            Label lbltxt = (Label)sender;
            GridDataItem container = (GridDataItem)lbltxt.NamingContainer;
            lbltxt.Text = ((DataRowView)container.DataItem)[colname].ToString();
        }

        public void textBox_DataBinding(object sender, EventArgs e)
        {
            TextBox txt = (TextBox)sender;
            GridDataItem container = (GridDataItem)txt.NamingContainer;
            txt.Text = ((DataRowView)container.DataItem)[colname].ToString();
        }
        public void searchtextBoxNoBORDER_DataBinding(object sender, EventArgs e)
        {
            RadTextBox txt = (RadTextBox)sender;
            GridDataItem container = (GridDataItem)txt.NamingContainer;
            txt.Text = ((DataRowView)container.DataItem)[colname].ToString();
        }

        public void searchtextBox_DataBinding(object sender, EventArgs e)
        {
            RadTextBox txt = (RadTextBox)sender;
            GridDataItem container = (GridDataItem)txt.NamingContainer;
            txt.Text = ((DataRowView)container.DataItem)[colname].ToString();
        }

        public void numerictextBox_DataBinding(object sender, EventArgs e)
        {
            RadNumericTextBox txt = (RadNumericTextBox)sender;
            GridDataItem container = (GridDataItem)txt.NamingContainer;
            txt.Text = ((DataRowView)container.DataItem)[colname].ToString();
        }

        public void linkbutton_DataBinding(object sender, EventArgs e)
        {
            LinkButton txt = (LinkButton)sender;
            GridDataItem container = (GridDataItem)txt.NamingContainer;
            txt.Text = ((DataRowView)container.DataItem)[colname].ToString();
        }

        public void radDate_DataBinding(object sender, EventArgs e)
        {
            RadDatePicker dtepicket = (RadDatePicker)sender;
            GridDataItem container = (GridDataItem)dtepicket.NamingContainer;
            if (((DataRowView)container.DataItem)[colname].ToString() != String.Empty)
            {
                dtepicket.SelectedDate = Convert.ToDateTime(((DataRowView)container.DataItem)[colname].ToString());
            }
        }

        # endregion

    }
    # endregion
}
//Enam decalaration for teleric Column Type ex like Textbox Column ,LinkButton Column
public enum TelerikControlType { TextBox, ComboBox, CheckBox, LinkButton, SearchTextBox, SearchTextBoxNOBORDER, NumericTextBox, RadDatePicker, Label, None, DIV,Image }

//Enum declaration for TelerikGrid Client Events
public enum clientEventType { gridCreated, rowClicked, rowDblClick, SearcButtonClick, ColumnClick, OnRowSelected, OnKeyPress, CellClicked }

For the controls i have created a ENUM for Textbox, Label, Combo box, Checkbox and etc. If I have missed any controls user can add there add those and use it in your project.

Now lets see how to use this in our ASP.net project.

1) Add the helperClass file in your App_Code Folder.

2) To create a Telerik Radgrid from Code Behind we need to declare the Telerik Rad grid as Public variable and in page load we need to provide the ID for the radgrid we can see here now a code part. We need to place a placeholder in our ASPX page where the radgrid need to be placed and add the radgrid to the placeholder from “ CS”.

// IN ASPX page
<telerik:radajaxmanager id="RadAjaxManager1" runat="server"/> 
<asp:placeholder id="PlaceHolder1" runat="server"/>
 #region Variables
// CS
    RadGrid RadGrid1 = new RadGrid();
   
    # endregion

 protected void Page_Load(object sender, EventArgs e)
    {

        RadGrid1.ID = "RadGrid1";
        this.PlaceHolder1.Controls.Add(RadGrid1);
   }

3)In page Init Method we can create a Radgrid using TelerikGridHelper Class. Here we can see  

" TelerikGridHelper.Layouts" this  method is used to set the layout of grid like autogenrated or not, Width, Height and etc.

"TelerikGridHelper.LayoutPage" this method is used to set the page size and allow paging true or false for the grid.

"TelerikGridHelper.ClientSetting" this method is used to set the client setting of grid like Allow Scroll, Allow Row Select and etc.

"TelerikGridHelper.ClientEvents" this method is used to declare the client events for the grid like row clicked and etc.

"TelerikGridHelper.ColumnGroups" this method is used to group the column header.

"TelerikGridHelper.Mastertableview" this method is used to set the Mastertableview.

" TelerikGridHelper.Templatecolumn" this method is used to set the Template column of grid. Same like this we have Bound Column, Image Column and etc setting.

 protected void Page_Init(object source, System.EventArgs e)
    {
        InitializeGridControl();
    }

    protected void InitializeGridControl()
    {
        TelerikGridHelper.Layouts(RadGrid1, 300, 98, true, false, false, false, false, false, true, false);
        TelerikGridHelper.LayoutPage(RadGrid1,4, true);
        TelerikGridHelper.ClientSetting(RadGrid1, false, false, false, false, false, false, 2);
        TelerikGridHelper.ClientSettingKEYBOARDNavi(RadGrid1, true, true, true);
        //grid events

        TelerikGridHelper.ClientEvents(RadGrid1, clientEventType.gridCreated, "GridCreated");
        TelerikGridHelper.ClientEvents(RadGrid1, clientEventType.rowClicked, "RowClick");
        TelerikGridHelper.ClientEvents(RadGrid1, clientEventType.rowDblClick, "RowDblClick");
        TelerikGridHelper.ClientEvents(RadGrid1, clientEventType.ColumnClick, "ColumnClick");
        TelerikGridHelper.ClientEvents(RadGrid1, clientEventType.OnRowSelected, "RowSelected");

        TelerikGridHelper.ColumnGroups(RadGrid1, "", "", "", HorizontalAlign.Center, 100);
        String[] keyname = { "Name" };
        TelerikGridHelper.Mastertableview(RadGrid1, keyname, false);

        //CheckBox Column
        TelerikGridHelper.Templatecolumn(RadGrid1, "", "chk", "chk", "", HorizontalAlign.Left, 20, false, TelerikControlType.CheckBox, "chkID", "", false, HorizontalAlign.Left, true);

        //Search Text Box 
        TelerikGridHelper.Templatecolumn(RadGrid1, "Search", "SearchID", "SearchID", "", HorizontalAlign.Left, 120, false, TelerikControlType.SearchTextBox, "txtSearchID", "", false, HorizontalAlign.Left, true);

        //Bound column
        TelerikGridHelper.BoundColumn(RadGrid1, "Name", "Name", "Name", "", HorizontalAlign.Left, 110, "", false, true, VerticalAlign.Bottom, HorizontalAlign.Left);

        //Numeric Text Box 
        TelerikGridHelper.Templatecolumn(RadGrid1, "Qty", "Qty", "Qty", "", HorizontalAlign.Left, 90, false, TelerikControlType.NumericTextBox, "txtQty", "", false, HorizontalAlign.Left, true);

        //Numeric Text Box 
        TelerikGridHelper.Templatecolumn(RadGrid1, "Price", "Price", "Price", "", HorizontalAlign.Left, 90, false, TelerikControlType.NumericTextBox, "txtamnt", "", false, HorizontalAlign.Left, true);

        //Numeric Text Box 
        TelerikGridHelper.Templatecolumn(RadGrid1, "TotalAmnt", "TotalAmnt", "TotalAmnt", "", HorizontalAlign.Left, 90, false, TelerikControlType.NumericTextBox, "txttotamnt", "", false, HorizontalAlign.Left, true);

        ////Bound column
        //TelerikGridHelper.BoundColumn(RadGrid1, "Display Amnt", "displayAmnt", "displayAmnt", "Totals", HorizontalAlign.Left, 110, "", false, true);

        //Label Column
        TelerikGridHelper.Templatecolumn(RadGrid1, "Item Name", "itemName", "itemName", "", HorizontalAlign.Left, 90, false, TelerikControlType.Label, "lblItemName", "", false, HorizontalAlign.Left, true);

        //DateTime Column
        TelerikGridHelper.Templatecolumn(RadGrid1, "Date", "Date", "Date", "", HorizontalAlign.Left, 130, false, TelerikControlType.RadDatePicker, "dtePicker", "", false, HorizontalAlign.Left, true);
        //Bound column
        TelerikGridHelper.BoundColumn(RadGrid1, "ID", "ID", "ID", "", HorizontalAlign.Left, 0, "", false, false, VerticalAlign.Bottom, HorizontalAlign.Left);
        //DropDownList
        TelerikGridHelper.Templatecolumn(RadGrid1, "Gender", "Gender", "Gender", "", HorizontalAlign.Left, 90, false, TelerikControlType.ComboBox, "ddlGender", "", false, HorizontalAlign.NotSet, true);
        //Push Button Column
        TelerikGridHelper.ButtonColumn(RadGrid1, "Button ", "ID", "", HorizontalAlign.Center, 60, "Click", GridButtonColumnType.PushButton , "ButtonCommand", "", true);

        //Link Button Column
        TelerikGridHelper.ButtonColumn(RadGrid1, "LinkButton ", "ID", "", HorizontalAlign.Center, 60, "Link Button", GridButtonColumnType.LinkButton, "linkCommand", "", true);

        //Image Button Column
        TelerikGridHelper.ButtonColumn(RadGrid1, "ImgButton ", "ID", "", HorizontalAlign.Center, 60, "Image Button", GridButtonColumnType.ImageButton, "imgCommand", "~/Images/icArrow_lov.gif", true);

        //grid events
        RadGrid1.NeedDataSource += new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
        RadGrid1.ItemCommand += new GridCommandEventHandler(RadGrid1_ItemCommand);
        RadGrid1.ItemDataBound += new GridItemEventHandler(RadGrid1_ItemDataBound);
        RadGrid1.ItemCreated += new GridItemEventHandler(RadGrid1_ItemCreated);
    }

Once the columns are all created the event of radgrid need to be declared in the init method as above. Here NeedDatasource event will be used to bind the Grid and etc.

4) Here we can see in “NeedDatasource” event we call the “SelectList” method to bind the grid .Next we can see the “RadGrid1_ItemDataBound” where we can bind the “Combo box” data source and client click events for controls inside the grid.

 protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        SelectList();

    }
 private void SelectList()
    {
        DataTable dt = (DataTable)Session["dt"];

       dt.DefaultView.RowFilter = "delStatus ='false'";
     
     TelerikGridHelper.DataBinds(RadGrid1, dt, true);

    }

  protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridHeaderItem)
        {
            GridHeaderItem item1 = e.Item as GridHeaderItem;
            CheckBox chkHeader = item1.FindControl("chkHeader") as CheckBox;

            chkHeader.Attributes.Add("onClick", "return checkAllRows()");

        }
        if (e.Item is GridDataItem)
        {
            GridDataItem item = e.Item as GridDataItem;

            RadNumericTextBox txtQty = item.FindControl("txtQty") as RadNumericTextBox;
            RadNumericTextBox txtamnt = item.FindControl("txtamnt") as RadNumericTextBox;
            RadNumericTextBox txttotamnt = item.FindControl("txttotamnt") as RadNumericTextBox;
            RadTextBox txtSearchBox = item.FindControl("txtSearchID") as RadTextBox;
            System.Web.UI.WebControls.Image R2ProjectImg = item.FindControl("imgtxtSearchID") as System.Web.UI.WebControls.Image;

            DropDownList ddlGender = item.FindControl("ddlGender") as DropDownList;

            Dictionary<string, string=""> States = new Dictionary<string, string="">();
            States.Add("-1", "Select");
            States.Add("M", "Male");
            States.Add("F", "Female");
            ddlGender.DataSource = States;
            ddlGender.DataValueField = "Key";
            ddlGender.DataTextField = "Value";
            ddlGender.DataBind();

            ddlGender.SelectedIndex = 0;


            Label lbltext = item.FindControl("lblItemName") as Label;
            int index = item.ItemIndex;

            txtQty.Attributes.Add("onChange", "return calculate('" + txtQty.ClientID + "','" + txtamnt.ClientID + "','" + txttotamnt.ClientID + "'," + index + ")");
            txtamnt.Attributes.Add("onChange", "return calculate('" + txtQty.ClientID + "','" + txtamnt.ClientID + "','" + txttotamnt.ClientID + "'," + index + ")");
            // txttotamnt.Attributes.Add("onfocus", "return calculate('" + txtQty.ClientID + "','" + txtamnt.ClientID + "','" + txttotamnt.ClientID + "'," + index + ")");
            txtSearchBox.Attributes.Add("onclick", "return searchTextBOXClicke('" + txtSearchBox.ClientID + "')");

            R2ProjectImg.Attributes.Add("onclick", "return searchTextBOXClick('" + txtSearchBox.ClientID + "');");
              
                

            //txttotamnt.ClientEvents.OnValueChanged = "Total";


        }
    }

Points of Interest

Hope this Telerik Grid Helper Class will be useful for the readers. If you like my article and found helpful for your project kindly leave me a comment and Vote my article. In my next article I have a plan to explain about the Helper Class for the Telerik Pivot Grid.

History

Version 1.0 - > 2014-09-04.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Visit My SHANU Blog
Mr.Shanu is a Senior Software Engineer. He’s basically from India and working at South Korea for more than 7 years.


He has 9+ years of Experience in Microsoft Technologies. More than 7 Years of experience in Automation Fields, He has worked in several projects of MES, Automation, ERP and HMI programs like PLC, Sensor, RFID and Nutrunner Tools. He has worked in both Windows based and Web Based projects.


Shanu Love to learn and work with new technology.


His main hobbies are to spend time with Family and to create Different and Innvotive programs and write Article about his program and Share with others.

His Latest Article which he likes most was Windows Form Design at Run Time

His facebook page
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionIs radajaxmanager part of the Telerik RadGrid Helper Class? PinmemberOscar R. Onorato28-Nov-14 5:23 
AnswerRe: Is radajaxmanager part of the Telerik RadGrid Helper Class? Pinprofessionalsyed shanu28-Nov-14 5:56 
GeneralRe: Is radajaxmanager part of the Telerik RadGrid Helper Class? PinmemberOscar R. Onorato28-Nov-14 6:30 
AnswerRe: Is radajaxmanager part of the Telerik RadGrid Helper Class? Pinprofessionalsyed shanu28-Nov-14 5:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 4 Sep 2014
Article Copyright 2014 by syed shanu
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid