This is a migrated thread and some comments may be shown as answers.

Grid healper Class

0 Answers 87 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Syed
Top achievements
Rank 1
Syed asked on 17 Oct 2013, 03:11 AM
hi,
I like to share my telerik Grid Helper class.
user can use this class to create there telerik grid by coding.
1) The Helper class for telerik grid,
I have created comman function like layout,page setting,client setting,data bind,master table setting,Image column,bound column,template column (Texxt box,link button,numerik text box,search box,lable),button column,

2) Simple ASpx design which has client event.here i used placeholdre where the radgrid will be added.This has header check box select all function.

3) CS file here you can see the actual code to call the helper class and data bindings .for more details see the code details.

1) TelerikGridHelper - class file :

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;
/// <summary>
/// Author      : Shanu
/// Create date : 2013-10-08
/// Description : telerikGridHelper
/// Latest
/// Modifier    : Shanu
/// Modify date : 2013-10-08
/// </summary>
public class TelerikGridHelper
{
    #region Variables

 

    #endregion
    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.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 = "RadDropDownList";
        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)
    {
        grid.ClientSettings.AllowColumnsReorder = ColumnReorder;
        grid.ClientSettings.ReorderColumnsOnClient = ReorderColumnsOnClient;
        grid.ClientSettings.EnableRowHoverStyle = true;
        grid.ClientSettings.Scrolling.AllowScroll = true;
        grid.ClientSettings.Scrolling.SaveScrollPosition = true;
        grid.ClientSettings.Scrolling.UseStaticHeaders = true;
        grid.ClientSettings.Scrolling.FrozenColumnsCount = 2;
        grid.ClientSettings.Resizing.EnableRealTimeResize = EnableRealTimeResize;
        grid.ClientSettings.Resizing.AllowColumnResize = AllowColumnResize;
        grid.ClientSettings.Selecting.AllowRowSelect = 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;
        
            }
       

    }
    #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;

    }
    #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)
    {
        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.Width = Width;
        boundColumn.Aggregate = GridAggregateFunction.None;
        boundColumn.Display = colDisplay;
        boundColumn.AllowFiltering = AllowFiltering;
     
        if (Aggregate != String.Empty)
        {
           // boundColumn.FooterText = Footertext;
            switch (Aggregate)
            {
                case "Sum":
                    boundColumn.Aggregate = GridAggregateFunction.Sum;
                    boundColumn.FooterAggregateFormatString = boundColumn.Aggregate.ToString() + ": {0:n}";
                    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

    //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)
    {
        if (Width <= 10)
        {
            Width = 20;
        }
        GridTemplateColumn templateColumn;
        templateColumn = new GridTemplateColumn();
        templateColumn.ItemTemplate = new MyTemplate(datafield, Columntype.ToString(), Width-2,contolID,CommandName);
        templateColumn.HeaderText = HeaderText;
        templateColumn.DataField = "datafield";
        templateColumn.UniqueName = UniqueName;

        if (groupName != String.Empty)
        {
            templateColumn.ColumnGroupName = groupName;
        }
        templateColumn.HeaderStyle.HorizontalAlign = Alignment;
        templateColumn.HeaderStyle.Width = Width;
     
     

        templateColumn.Aggregate = GridAggregateFunction.None;
     
        templateColumn.AllowFiltering = AllowFiltering;
              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 RadNumericTextBox numericTextBox;
        protected RadDatePicker radDate;
        protected Label label;
        //loacl variable
        private String colname;
        private String Columntype;
        private int cntrlwidth;
        private String cntrlId;
        private String CmdName;

        # endregion

        #region bindControls

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

        public void InstantiateIn(System.Web.UI.Control container)
        {
            switch (Columntype)
           {
              case  "TextBox":
         
                textBox = new TextBox();
                textBox.ID = cntrlId;
                textBox.Width = cntrlwidth;
                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-10;
                    searchTextBox.ShowButton=true;
                searchTextBox.DataBinding += new EventHandler(searchtextBox_DataBinding);
                //validatorTextBox = new RequiredFieldValidator();
                //validatorTextBox.ControlToValidate = cntrlId;
                //validatorTextBox.ErrorMessage = "*";
                container.Controls.Add(searchTextBox);
                //container.Controls.Add(validatorTextBox);
               break;

               case "NumericTextBox":

               numericTextBox = new RadNumericTextBox();
               numericTextBox.ID = cntrlId;
               numericTextBox.Width = cntrlwidth;
               numericTextBox.AutoCompleteType = AutoCompleteType.None;
               numericTextBox.Type = NumericType.Number;
               numericTextBox.ShowSpinButtons = false;
               numericTextBox.AllowOutOfRangeAutoCorrect = false;
              // 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;
                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);

                container.Controls.Add(boolValue);
               break;

           case "ComboBox":
                combobox = new DropDownList();
                combobox.ID = cntrlId;
                combobox.Width = cntrlwidth;
                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;
              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 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, NumericTextBox, RadDatePicker, Label,None,DIV }

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



2) ASPX Page

<asp:Content ID="Content2" runat="server" ContentPlaceHolderID="cphBody">
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
            //<![CDATA[

           
            var isChecked = false;

            var radGrid;

            function GridCreated(sender, eventArgs) {
                radGrid = sender;
            }
         
            function checkAllRows() {
                var totalRows = radGrid.get_masterTableView().get_element().tBodies[0].rows.length - 1;
                isChecked = !isChecked;
                for (i = 0; i <= totalRows; i++) {
                    if (isChecked) {
                        $telerik.findElement(radGrid.MasterTableView.get_dataItems()[i].get_element(), "chkID").checked = true;
                    }
                    else {
                        $telerik.findElement(radGrid.MasterTableView.get_dataItems()[i].get_element(), "chkID").checked = false;
                    }
                }
            }
            function calculate(cntQty, cntprice, cntamnt, rowindex)
            {
               var text1 = $find(cntQty);
               var text2 = $find(cntprice);
               var text3 = $find(cntamnt);
               // alert(rowindex);
            
                var total = text1.get_value() * text2.get_value();
                text3.set_value(total);
             
                //radGrid.MasterTableView.get_dataItems()[rowindex].get_cell("displayAmnt").innerHTML = total;
            }

           

            function RowClick(sender, eventArgs) {
                var text = "";
                text += "Row was clicked";
                text += ", Index: " + eventArgs.get_itemIndexHierarchical();
                 alert(text);
             }

          

            function RowDblClick(sender, eventArgs) {
                var text = "";
                text += "Row was double clicked";
                text += ", Index: " + eventArgs.get_itemIndexHierarchical();
                alert(text);
            }

            function ColumnClick(sender, eventArgs) {
                var text = "";
                text += "Column was clicked";
                text += ", Index: " + eventArgs.get_gridColumn().get_element().cellIndex;
                alert(text);
            }

            function RowSelected(sender, args) {
                var masterTable = sender.get_masterTableView();
                var row = masterTable.get_dataItems();
                var indexs = args.get_itemIndexHierarchical()
             

                alert("Row Qty Value : "+masterTable.get_dataItems()[indexs].findControl("txtQty").get_value());
                alert(masterTable.get_dataItems()[indexs].get_cell("Name").innerHTML);
               // masterTable.get_dataItems()[indexs].get_cell("displayAmnt").innerHTML = masterTable.get_dataItems()[indexs].findControl("txttotamnt").get_value();
                //alert("<b>Total Amount: </b>" + args.getDataKeyValue("displayAmnt"));
               
            }

            function searchTextBOXClick(sender, eventArgs) {
                var senderid = sender.get_id();

                var strtext = $find(senderid).get_value();
                alert(strtext);
                window.radopen("TelerikDataBind.aspx", "UserListDialog");
            } 

         //]]>
        </script>
    </telerik:RadCodeBlock>
    <table style='width: 99%;table-layout:fixed;'>
   <tr>
       <td>
         <table >
             <tr>
               
                    <td  >
                        <telerik:RadButton ID="DatumButton" runat="server" Text="test" onclick="DatumButton_Click"  >
                      
                        </telerik:RadButton>          
          
                    </td>
                    <td>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </td>
             </tr>
        </table>
    </td>
   </tr>

   <tr>
     <td>Details : </td>
   </tr>
  <tr>
  <td>
   <table>
                                <tr>
                                                                
                                    <td width="30">
                                        <asp:ImageButton ID="btnRowAdd" runat="server"
                                        ImageUrl="~/Images/Button/btnRowAdd.gif" onclick="btnRowAdd_Click"  />
                                    </td>
                                    <td width="30">
                                        <asp:ImageButton ID="btnRowDel" runat="server"
                                        ImageUrl="~/Images/Button/btnRowDelete.gif" onclick="btnRowDel_Click" />               
                                    </td>                   
                                
                                </tr>
                            </table>
  </td>
  </tr>
   <tr>
    <td >  
    <table >
    <tr>
     <td> 
           <%--<telerik:RadGrid ID="RadGrid1" runat="server">
           </telerik:RadGrid>--%>
            <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        </telerik:RadAjaxManager>
           <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
       </td>
    </tr>
   </table>
   </td>
   </tr>
   </table>

    <telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableShadow="true">
        <Windows>
            <telerik:RadWindow ID="UserListDialog" runat="server" Title="Editing record" Height="600px"
                Width="1024px"  ReloadOnShow="true" ShowContentDuringLoad="false"
                Modal="true">
            </telerik:RadWindow>
        </Windows>
    </telerik:RadWindowManager>

</asp:Content>

3) CS File the

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

public partial class TelerikGridClientEvents : System.Web.UI.Page
{


#region Variables
    RadGrid RadGrid1 = new RadGrid();
    Boolean headerControl=false;
    # endregion
    #region PageLoad
    protected void Page_Load(object sender, EventArgs e)
    {
         RadGrid1.ID = "RadGrid1";
        this.PlaceHolder1.Controls.Add(RadGrid1);

        if (!IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("chk");
            dt.Columns.Add("ID");
            dt.Columns.Add("SearchID");
            dt.Columns.Add("Name");
            dt.Columns.Add("Qty");
            dt.Columns.Add("Price");
            dt.Columns.Add("TotalAmnt");
            dt.Columns.Add("itemName");
            dt.Columns.Add("Date");
            dt.Columns.Add("delStatus");
           

            dt.Rows.Add(1, 1,1, "Name1", 4, 3, 12,"item 1","2013-02-08", false);
            dt.Rows.Add(2, 2,2, "Naem2", 5, 3, 15, "item 2", "2013-06-09", false);
            dt.Rows.Add( 3,3,3, "Name3", 4, 6, 24, "Item 3", "2013-06-03", false);
            Session["dt"] = dt;

            SelectList();
           
        }
      
        RadAjaxManager1.AjaxSettings.AddAjaxSetting(RadGrid1, RadGrid1);
        RadAjaxManager1.AjaxSettings.AddAjaxSetting(btnRowAdd, RadGrid1);
        RadAjaxManager1.AjaxSettings.AddAjaxSetting(btnRowDel, RadGrid1);
        RadAjaxManager1.AjaxSettings.AddAjaxSetting(RadGrid1, TextBox1);
    }
    protected void Page_Init(object source, System.EventArgs e)
    {
        InitializeGridControl();
    }

    protected void InitializeGridControl()
    {
        TelerikGridHelper.Layouts(RadGrid1, 400, 98,true, false,false,false,false,false,true,false);
        TelerikGridHelper.LayoutPage(RadGrid1, 20,false);
        TelerikGridHelper.ClientSetting(RadGrid1, false, false,false, false);
        //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", "");

      

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

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

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

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

        //Numeric Text Box
        TelerikGridHelper.Templatecolumn(RadGrid1, "TotalAmnt", "TotalAmnt", "TotalAmnt", "", HorizontalAlign.Left, 90, false, TelerikControlType.NumericTextBox, "txttotamnt", "");
       
        ////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, "lblamount", "");

        //DateTime Column
        TelerikGridHelper.Templatecolumn(RadGrid1, "Date", "Date", "Date", "", HorizontalAlign.Left, 130, false, TelerikControlType.RadDatePicker, "dtePicker", "");
        //Bound column
        TelerikGridHelper.BoundColumn(RadGrid1, "ID", "ID", "ID", "", HorizontalAlign.Left, 0, "", false, false);
       
        //Push Button Column
        TelerikGridHelper.ButtonColumn(RadGrid1, "Push Button ",  "ID", "", HorizontalAlign.Center, 100, "Click",GridButtonColumnType.PushButton, "ButtonCommand","", true);

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

        //Image Button Column
        TelerikGridHelper.ButtonColumn(RadGrid1, "Push Button ", "ID", "", HorizontalAlign.Center, 100, "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);
    }
    # endregion

    # region Methods
    private void SelectList()
    {

        DataTable dt = (DataTable)Session["dt"];

        //DataView dv = new DataView(dt);
        //dv.RowFilter = "delStatus ='false'";
        dt.DefaultView.RowFilter = "delStatus ='false'";
        //RadGrid1.DataSource = dv;
        //RadGrid1.DataBind();
        TelerikGridHelper.DataBinds(RadGrid1, dt, false);

    }
    # endregion

    # region Page Events
    protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == "ButtonCommand")
        {
            GridDataItem item = e.Item as GridDataItem;
            item.Selected = true;

            Label linkBtn = item.FindControl("lblamount") as Label;
            TextBox1.Text = linkBtn.Text;
        }
        else if (e.CommandName == "linkCommand")
        {
            GridDataItem item = e.Item as GridDataItem;
            item.Selected = true;

            Label linkBtn = item.FindControl("lblamount") as Label;
            TextBox1.Text = linkBtn.Text;
        }
        else if (e.CommandName == "imgCommand")
        {
            GridDataItem item = e.Item as GridDataItem;
            item.Selected = true;

            Label linkBtn = item.FindControl("lblamount") as Label;
            TextBox1.Text = linkBtn.Text;
        }
    }

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

    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridHeaderItem)
        {
            GridHeaderItem item = (GridHeaderItem)e.Item;
          CheckBox  boolValue = new CheckBox();
            boolValue.ID = "chkHeader";

            TableCell cell = (TableCell)item["chk"];
          
                cell.Controls.Add(boolValue);
                headerControl = 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;
         
            Label lbltext = item.FindControl("lblamount") 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.ClientEvents.OnButtonClick = "searchTextBOXClick";

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

        }
    }
 
    protected void DatumButton_Click(object sender, EventArgs e)
    {

    }
 
    protected void btnRowAdd_Click(object sender, ImageClickEventArgs e)
    {
        DataTable dt = (DataTable)Session["dt"];

        for (int i = 0; i < RadGrid1.Items.Count; i++)
        {
            CheckBox chkSelected = (CheckBox)RadGrid1.Items[i].FindControl("chkID");
            RadNumericTextBox txtQty = (RadNumericTextBox)RadGrid1.Items[i].FindControl("txtQty"); //item.FindControl("txtQty") as RadNumericTextBox;
            RadNumericTextBox txtamnt = (RadNumericTextBox)RadGrid1.Items[i].FindControl("txtamnt"); //item.FindControl("txtamnt") as RadNumericTextBox;
            RadNumericTextBox txttotamnt = (RadNumericTextBox)RadGrid1.Items[i].FindControl("txttotamnt"); //item.FindControl("txttotamnt") as RadNumericTextBox;

            String Id = RadGrid1.Items[i]["ID"].Text;
            DataRow[] drr = dt.Select("ID='" + Id + "'");

            if (drr != null)
            {
                drr[0]["Qty"] = txtQty.Text;
                drr[0]["Price"] = txtamnt.Text;
                drr[0]["TotalAmnt"] = txttotamnt.Text;

                if (chkSelected.Checked && chkSelected != null)
                {
                    drr[0]["delStatus"] = "true";
                }

            }
            dt.AcceptChanges();
        }

        int ids=dt.Rows.Count+1;
        DataRow drnew = dt.NewRow();

        drnew["chk"] = ids.ToString();
        drnew["ID"] = ids.ToString();
        drnew["SearchID"] = ids.ToString();
        drnew["Name"] = "Name " + ids.ToString();
        drnew["Qty"] = "0";
        drnew["Price"] = "0";
        drnew["TotalAmnt"] = "0";
        drnew["itemName"] = "Item  " + ids.ToString();
        drnew["Date"] = DateTime.Today.ToString();
        drnew["delStatus"] = "false";

        dt.Rows.Add(drnew);
        dt.AcceptChanges();
        //RadGrid1.Rebind();
        SelectList();
    }
 
    protected void btnRowDel_Click(object sender, ImageClickEventArgs e)
    {
    

        for (int i = 0; i < RadGrid1.Items.Count; i++)
        {
            CheckBox chkSelected = (CheckBox)RadGrid1.Items[i].FindControl("chkID");
            RadNumericTextBox txtQty = (RadNumericTextBox)RadGrid1.Items[i].FindControl("txtQty"); //item.FindControl("txtQty") as RadNumericTextBox;
            RadNumericTextBox txtamnt = (RadNumericTextBox)RadGrid1.Items[i].FindControl("txtamnt"); //item.FindControl("txtamnt") as RadNumericTextBox;
            RadNumericTextBox txttotamnt = (RadNumericTextBox)RadGrid1.Items[i].FindControl("txttotamnt"); //item.FindControl("txttotamnt") as RadNumericTextBox;

            String Id = RadGrid1.Items[i]["ID"].Text;

            DataTable dt = (DataTable)Session["dt"];
            DataRow[] drr = dt.Select("ID='" + Id + "'");
          
                    if (drr != null)
                    {
                        drr[0]["Qty"] = txtQty.Text;
                        drr[0]["Price"] = txtamnt.Text;
                        drr[0]["TotalAmnt"] = txttotamnt.Text;

                         if (chkSelected.Checked && chkSelected != null)
                         { 
                        drr[0]["delStatus"] = "true";
                         }
                  
                }
                dt.AcceptChanges();            
            }
      
        SelectList();
        //RadGrid1.Rebind();
    }

    # endregion
}


hope this grid helper class will be helpfull for the users who do programatic creation of radgrid.

No answers yet. Maybe you can help?

Tags
Grid
Asked by
Syed
Top achievements
Rank 1
Share this question
or