65.9K
CodeProject 正在变化。 阅读更多。
Home

Telerik RadGrid 辅助类 for ASP.NET

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (7投票s)

2015年1月28日

CPOL

5分钟阅读

viewsIcon

58941

downloadIcon

1649

如何为 ASP.NET 中的 Telerik Radgrid 创建辅助类

引言

在本文中,我将解释如何为 ASP.NET 中的 Telerik Radgrid 创建一个辅助类。在我的一项 Web 项目中,我正在使用 Telerik 网格。当我的项目开始时,我在 Telerik 网站上寻找 RadGrid 的辅助类,并使用 Google 来获取一个辅助类。但我找不到任何 Telerik Radgrid 的辅助类。所以我计划为 Telerik Rad Grid 创建一个辅助类。因此,我创建了一个 Telerik Radgrid 的辅助类。我想与他人分享我的辅助类,以便他们可以在他们的项目中使用我的类,并使代码变得简单易用。

为什么我们需要辅助类

  • 辅助类将使我们的代码部分简单而标准化。
  • ASPX 页面中不再需要 Radgrid 设计。所有操作都可以在 CS 部分完成。
  • 类中一次性的设计可以用于整个项目。
  • 如果我们只在类文件中更改设计,而无需在每个页面上重新设计,这将非常有用。

注意:在我的示例中,我使用了 Telerik ASP.NET 版本 2013.3.1114.40。我已从 zip 文件中移除了我的 Telerik DLL。如果您想运行我的示例程序,您需要将您的 Telerik DLL 添加到我的项目中。您可以从 Telerik 网站下载 Telerik 的试用版或购买完整版。

在此示例项目中,我创建了一个带有我的辅助类的 ASP.NET 示例程序。在我的示例程序中,我还解释了 Radgrid 的基本 JavaScript 事件以及列标题的复选框选中事件。以下是 Radgrid 搜索框列单击事件中显示 JavaScript 消息的示例。

Using the Code

首先,我们可以从辅助类开始,然后我们可以看看如何在 ASP.NET 页面中使用辅助类。在我的辅助类中,我具有以下函数来使设计和绑定变得简单。

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

我们可以看几个重要的类函数,然后我将在此处粘贴我的完整类代码。

布局

此方法将设置网格的 SkinHeightwidth 等。width 可以设置为百分比或值,如果 width 类型为 false,则使用值,如果为 true,则使用百分比来显示网格。

 #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 generated 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 
                                                               // individual columns
       
        grid.Height = height;               // Set the height of the grid  in % or in pixel
        if (width > 0)
        {
            if (widthtype == false)
            {
                grid.Width = width;         // set the Width of the grid  in % or in pixel
            }
            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

此方法可用于设置 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,则可以调用 Bound column 方法。用户可以从“cs”页面将所有参数传递给此类以使用 boundcolumn

 //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 完整源代码

这是 Telerik Grid 辅助类的完整源代码。我已经创建了所有必需的方法。如果用户需要更多,他们也可以在这里为这个类添加这些函数并在您的项目中使用。在这个辅助类中,我们可以看到一个“MyTemplate”类,它将用于绑定模板列和按钮列以将控件绑定到网格。

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 generated 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 
                                                               // individual columns
       
        grid.Height = height; //Set the height of the grid  in % or in pixel
        if (width > 0)
        {
            if (widthtype == false)
            {
                grid.Width = width;   // set the Width of the grid  in % or in pixel
            }
            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 declare 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 than 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, 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 telerik 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;

        //local 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
}
//Enum declaration for telerik 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 }

对于控件,我已经为 TextboxLabelComboboxCheckbox 等创建了一个 ENUM。如果我遗漏了任何控件,用户可以添加它们,并在您的项目中添加并使用它们。

现在让我们看看如何在我们的 ASP.NET 项目中使用它。

  1. helperClass 文件添加到您的 App_Code 文件夹。
  2. 要从代码隐藏创建 Telerik Radgrid,我们需要将 Telerik Rad grid 声明为 Public 变量,并在页面加载时,我们需要为 radgrid 提供 ID,我们可以在此处看到代码部分。我们需要在 ASPX 页面上放置一个占位符,其中需要放置 radgrid,并从“CS”将 radgrid 添加到占位符。
    // 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. 在页面 Init 方法中,我们可以使用 TelerikGridHelper 类创建 Radgrid。在这里,我们可以看到
    • "TelerikGridHelper.Layouts": 此方法用于设置网格的布局,例如是否自动生成,WidthHeight 等。
    • "TelerikGridHelper.LayoutPage": 此方法用于设置网格的分页大小并允许分页 truefalse
    • "TelerikGridHelper.ClientSetting": 此方法用于设置网格的客户端设置,例如允许滚动,允许行选择等。
    • "TelerikGridHelper.ClientEvents": 此方法用于为网格声明客户端事件,例如行点击等。
    • "TelerikGridHelper.ColumnGroups": 此方法用于对列标题进行分组。
    • "TelerikGridHelper.Mastertableview": 此方法用于设置 Mastertableview
    • " TelerikGridHelper.Templatecolumn": 此方法用于设置网格的模板列。类似地,我们有 Bound Column,Image Column 等设置。
     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);
        }

    一旦所有列都创建完毕,就需要如上所述在 init 方法中声明 radgrid 的事件。在这里,NeedDatasource 事件将用于绑定 Grid 等。

  4. 在这里,我们可以看到在“NeedDatasource”事件中,我们调用“SelectList”方法来绑定网格。接下来,我们可以看到“RadGrid1_ItemDataBound”,我们可以在其中绑定“Combo box”数据源和网格内控件的客户端点击事件。
     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";
            }
        }

关注点

希望这个 Telerik Grid 辅助类能对读者有所帮助。如果您喜欢我的文章,并发现它对您的项目有所帮助,请给我留言并投票。在我的下一篇文章中,我计划介绍 Telerik Pivot Grid 的辅助类。

历史

  • 2014 年 9 月 4 日:版本 1.0
© . All rights reserved.