Introduction
In this article, I will explain how to create a Helper Class for Telerik Radgrid in ASP.NET. In one of my web projects, I‘m using Telerik grid. When I started my project, I was looking for a Helper Class for RadGrid at Telerik Site and used Google to get one Helper Class. But I couldn’t find 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 their project and make a code simple and easy.
Why Do 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 used Telerik ASP.NET Version 2013.3.1114.40. I 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 a sample ASP.NET program with my helper class. In my sample program, I have also explained 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 following 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, etc. The width
can be set as percentage or as value, if the width
type is false
, then use as the value 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;
grid.Skin = "Office2007";
grid.AllowMultiRowSelection = multirowselect;
grid.AllowSorting = allowsorting;
grid.GridLines = GridLines.Both;
grid.ShowStatusBar = showstatusbar;
grid.AllowFilteringByColumn = allowfilteringbycolumns;
grid.Height = height;
if (width > 0)
{
if (widthtype == false)
{
grid.Width = width;
}
else
{
grid.Width = Unit.Percentage(width);
}
}
grid.ShowGroupPanel = showgrouppannel;
grid.ShowHeader = ShowHeader;
grid.ShowFooter = ShowFooter;
}
#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;
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 parameters from the “cs
” page to this class to use the boundcolumn
.
#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)
{
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;
}
}
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 needs 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;
public class TelerikGridHelper
{
public TelerikGridHelper()
{ }
#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;
grid.Skin = "Office2007";
grid.AllowMultiRowSelection = multirowselect;
grid.AllowSorting = allowsorting;
grid.GridLines = GridLines.Both;
grid.ShowStatusBar = showstatusbar;
grid.AllowFilteringByColumn = allowfilteringbycolumns;
grid.Height = height;
if (width > 0)
{
if (widthtype == false)
{
grid.Width = width;
}
else
{
grid.Width = Unit.Percentage(width);
}
}
grid.ShowGroupPanel = showgrouppannel;
grid.ShowHeader = ShowHeader;
grid.ShowFooter = ShowFooter;
}
#endregion
#region LayoutPage
public static void LayoutPage(RadGrid grid, int pagesize, Boolean allowpaging)
{
grid.PageSize = pagesize;
grid.AllowPaging = allowpaging;
grid.PagerStyle.PageSizeControlType = PagerDropDownControlType.None;
grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
}
#endregion
#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;
}
#endregion
#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;
}
#endregion
#region ClientEvents
public static void ClientEvents
(RadGrid grid, clientEventType clienteventtype, String clientfunctionname)
{
switch (clienteventtype.ToString())
{
case "gridCreated":
grid.ClientSettings.ClientEvents.OnGridCreated =
clientfunctionname;
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
#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
#region GridMasterTableSetting
public static void Mastertableview
(RadGrid grid, String[] keyvalue, Boolean allowfilteringbycolumn)
{
if (keyvalue[0] != String.Empty)
{
grid.MasterTableView.DataKeyNames = keyvalue;
grid.MasterTableView.ClientDataKeyNames = keyvalue;
}
grid.MasterTableView.EnableHeaderContextMenu = true;
grid.MasterTableView.AllowFilteringByColumn = allowfilteringbycolumn;
grid.MasterTableView.Font.Size = 9;
grid.MasterTableView.TableLayout = GridTableLayout.Fixed;
grid.MasterTableView.ShowGroupFooter = true;
grid.MasterTableView.ShowFooter = true;
}
#endregion
#region gridColumnType
#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
#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)
{
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;
}
}
grid.MasterTableView.Columns.Add(boundColumn);
}
#endregion
#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;
if (Aggregate != String.Empty)
{
switch (Aggregate)
{
case "Sum":
boundColumn.Aggregate = GridAggregateFunction.Sum;
boundColumn.FooterAggregateFormatString = FooterText + "{0:n}";
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;
case "None":
boundColumn.Aggregate = GridAggregateFunction.None;
boundColumn.FooterAggregateFormatString = FooterText ;
boundColumn.FooterText = FooterText;
boundColumn.FooterStyle.Font.Bold = true;
break;
}
}
grid.MasterTableView.Columns.Add(boundColumn);
}
#endregion
#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
#region Templatecolumn
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;
grid.MasterTableView.Columns.Add(templateColumn);
}
#endregion
#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
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;
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);
container.Controls.Add(textBox);
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);
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);
container.Controls.Add(searchTextBoxNOBRDR);
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.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)
{
}
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
}
public enum TelerikControlType { TextBox, ComboBox, CheckBox,
LinkButton, SearchTextBox, SearchTextBoxNOBORDER, NumericTextBox,
RadDatePicker, Label, None, DIV,Image }
public enum clientEventType { gridCreated, rowClicked, rowDblClick,
SearcButtonClick, ColumnClick, OnRowSelected, OnKeyPress, CellClicked }
For the controls, I have created an ENUM
for Textbox
, Label
, Combobox
, Checkbox
, etc. If I have missed any controls user can add there, add those and use them in your project.
Now let's see how to use this in our ASP.NET project.
- Add the
helperClass
file in your App_Code Folder. - 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 needs 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
RadGrid RadGrid1 = new RadGrid();
# endregion
protected void Page_Load(object sender, EventArgs e)
{
RadGrid1.ID = "RadGrid1";
this.PlaceHolder1.Controls.Add(RadGrid1);
}
- 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 auto generated or not, Width
, Height
, 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, etc. - "
TelerikGridHelper.ClientEvents
": This method is used to declare the client events for the grid like row clicked, 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. Similar to this, we have Bound Column, Image Column, 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);
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);
TelerikGridHelper.Templatecolumn(RadGrid1, "", "chk", "chk", "",
HorizontalAlign.Left, 20, false, TelerikControlType.CheckBox,
"chkID", "", false, HorizontalAlign.Left, true);
TelerikGridHelper.Templatecolumn(RadGrid1, "Search", "SearchID",
"SearchID", "", HorizontalAlign.Left, 120, false,
TelerikControlType.SearchTextBox, "txtSearchID", "",
false, HorizontalAlign.Left, true);
TelerikGridHelper.BoundColumn(RadGrid1, "Name", "Name",
"Name", "", HorizontalAlign.Left, 110, "", false, true,
VerticalAlign.Bottom, HorizontalAlign.Left);
TelerikGridHelper.Templatecolumn(RadGrid1, "Qty", "Qty",
"Qty", "", HorizontalAlign.Left, 90, false,
TelerikControlType.NumericTextBox, "txtQty", "",
false, HorizontalAlign.Left, true);
TelerikGridHelper.Templatecolumn(RadGrid1, "Price", "Price",
"Price", "", HorizontalAlign.Left, 90,
false, TelerikControlType.NumericTextBox,
"txtamnt", "", false, HorizontalAlign.Left, true);
TelerikGridHelper.Templatecolumn(RadGrid1, "TotalAmnt", "TotalAmnt",
"TotalAmnt", "", HorizontalAlign.Left, 90, false,
TelerikControlType.NumericTextBox, "txttotamnt", "",
false, HorizontalAlign.Left, true);
TelerikGridHelper.Templatecolumn(RadGrid1, "Item Name", "itemName",
"itemName", "", HorizontalAlign.Left, 90, false, TelerikControlType.Label,
"lblItemName", "", false, HorizontalAlign.Left, true);
TelerikGridHelper.Templatecolumn(RadGrid1, "Date", "Date", "Date",
"", HorizontalAlign.Left, 130, false, TelerikControlType.RadDatePicker,
"dtePicker", "", false, HorizontalAlign.Left, true);
TelerikGridHelper.BoundColumn(RadGrid1, "ID", "ID", "ID", "",
HorizontalAlign.Left, 0, "", false, false,
VerticalAlign.Bottom, HorizontalAlign.Left);
TelerikGridHelper.Templatecolumn(RadGrid1, "Gender", "Gender",
"Gender", "", HorizontalAlign.Left, 90, false, TelerikControlType.ComboBox,
"ddlGender", "", false, HorizontalAlign.NotSet, true);
TelerikGridHelper.ButtonColumn(RadGrid1, "Button ", "ID", "",
HorizontalAlign.Center, 60, "Click", GridButtonColumnType.PushButton ,
"ButtonCommand", "", true);
TelerikGridHelper.ButtonColumn(RadGrid1, "LinkButton ", "ID", "",
HorizontalAlign.Center, 60, "Link Button", GridButtonColumnType.LinkButton,
"linkCommand", "", true);
TelerikGridHelper.ButtonColumn(RadGrid1, "ImgButton ", "ID", "",
HorizontalAlign.Center, 60, "Image Button", GridButtonColumnType.ImageButton,
"imgCommand", "~/Images/icArrow_lov.gif", true);
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 needs to be declared in the init
method as above. Here, NeedDatasource
event will be used to bind the Grid, etc.
- 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 + ")");
txtSearchBox.Attributes.Add("onclick",
"return searchTextBOXClicke('" + txtSearchBox.ClientID + "')");
R2ProjectImg.Attributes.Add("onclick", "return searchTextBOXClick
('" + txtSearchBox.ClientID + "');");
}
}
Points of Interest
Hope this Telerik Grid Helper class will be useful for readers. If you liked my article and found it helpful for your project, kindly leave me a comment and vote for my article. In my next article, I am planning to explain about the Helper Class for the Telerik Pivot Grid.
History
- 4th September, 2014: Version 1.0