RadGrid for ASP.NET

Programmatic creation Send comments on this topic.
Defining Structure > Programmatic creation

Glossary Item Box

You have two options for creating your RadGrid instance dynamically. 

Create Telerik RadGrid entirely in the code behind.

This means that the RadGrid instance should be created in the PageInit handler and added to a place holder's Controls collection at runtime, after the structure has been created. Note that in this case the grid columns should be added to the Controls collection of the MasterTableView after their attributes are set. No ViewState is required for grid structure to be persisted as it is recreated on each page initialization. There are no other special requirements in this case:

C# Copy Code
PlaceHolder PlaceHolder1;

RadGrid RadGrid1 = new RadGrid();

RadGrid1.NeedDataSource +=
new GridNeedDataSourceEventHandler(this.RadGrid1_NeedDataSource);
RadGrid1.DetailTableDataBind +=
new GridDetailTableDataBindEventHandler(this.RadGrid1_DetailTableDataBind);

RadGrid1.Skin=
"Default";
RadGrid1.Width = Unit.Percentage(100);
RadGrid1.PageSize = 5;
RadGrid1.AllowPaging = true;
RadGrid1.AutoGenerateColumns = false;
RadGrid1.GroupingEnabled = true;
RadGrid1.ShowGroupPanel = true;
RadGrid1.ClientSettings.AllowDragToGroup = true;
RadGrid1.MasterTableView.DataMember =
"Customers";
RadGrid1.MasterTableView.PageSize = 15;

GridBoundColumn boundColumn;
boundColumn =
new GridBoundColumn();
boundColumn.DataField =
"CustomerID";
boundColumn.HeaderText =
"CustomerID";
RadGrid1.MasterTableView.Columns.Add(boundColumn);

....
//Add to page controls collection
this.PlaceHolder1.Controls.Add( RadGrid1 );
        


VB.NET Copy Code
Dim PlaceHolder1 as PlaceHolder

Dim RadGrid1 as RadGrid = New RadGrid

AddHandler RadGrid1.NeedDataSource, AddressOf Me.RadGrid1_NeedDataSource
AddHandler RadGrid1.DetailTableDataBind, AddressOf Me.RadGrid1_DetailTableDataBind

RadGrid1.Skin= "Default"
RadGrid1.Width = Unit.Percentage(100)
RadGrid1.PageSize = 5
RadGrid1.AllowPaging = true
RadGrid1.AutoGenerateColumns = false
RadGrid1.GroupingEnabled = true
RadGrid1.ShowGroupPanel = true
RadGrid1.ClientSettings.AllowDragToGroup = true
RadGrid1.MasterTableView.DataMember = "Customers"
RadGrid1.MasterTableView.PageSize = 15

Dim boundColumn As GridBoundColumn
boundColumn = New GridBoundColumn
boundColumn.DataField = "CustomerID"
boundColumn.HeaderText = "CustomerID"
RadGrid1.MasterTableView.Columns.Add(boundColumn)

....'Add to page controls collection
PlaceHolder1.Controls.Add(RadGrid1)


Create Telerik RadGrid statically, but add its structure dynamically.

  1. This should take place in the PageLoad event handler, following the rules for a structure object: columns or detail table should be added to the corresponding collection first and then values for the properties of this instance should be set. Remember to check the condition (Not IsPostBack) to avoid adding the same structure objects to RadGrid twice. This is important because no ViewState is managed for the object before it has been added to the corresponding collection.

    Example:

    C# Copy Code
    private void Page_Load(object sender, System.EventArgs e)
    {
     
    if ( !IsPostBack )
     {
       GridBoundColumn boundColumn;

       
    //Important: first Add column to the collection
       
    boundColumn = new GridBoundColumn();
       
    this.RadGrid1.MasterTableView.Columns.Add(boundColumn);

       
    //Then set properties
       
    boundColumn.DataField = "CustomerID";
       boundColumn.HeaderText =
    "CustomerID";
     }
    }
                    
    VB.NET Copy Code
    Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
     If Not IsPostBack Then
      Dim boundColumn As GridBoundColumn

      'Important: first Add column to the collection
      boundColumn = New GridBoundColumn
      Me.RadGrid1.MasterTableView.Columns.Add(boundColumn)

      'Then set properties
      boundColumn.DataField = "CustomerID"
      boundColumn.HeaderText = "CustomerID"
     End If
    End Sub
  2. The VB.NET language gives one more option (unavailable in C#). You can have the grid instance created on the page but you can handle the RadGrid.Init event and create dynamically structure similar to the one depicted in point 1.

 

Note: Creating columns on PageLoad when !Page.IsPostBack is not a problem for all column types except for GridTemplateColumns. In order to persist their ViewState you need to generate your grid completely in the code-behind (on PageInit). Thus the template controls will be retained as they will be instantiated before LoadViewState event of the page.


 

 

Note: Telerik RadGrid does not support mixed load for grid columns (declarative and runtime combination). You should either create all your grid columns programmatically or define all columns statically in the html code of the page. Mixing the modes for column generation may cause abnormalities in the grid behavior (column duplication, errors on performing built-in operations, etc.).


Create hierarchical grid programmatically

Here are the basic steps that you need to follow in order to create hierarchical Telerik RadGrid programmatically in the code-behind (having data source control for data content generation):

  1. Create the grid dynamically in the PageInit handler of the page by calling its constructor.
  2. Specify the preferred settings for your grid instance through its properties.
  3. Create columns for the grid dynamically. Keep in mind that you have to first set their properties and then add them to the MasterTableView/GridTableView collection (discussed in the first paragraph of this topic). Thus their ViewState will be properly persisted (as LoadViewState is raised after the Init event of the page)
  4. Set properly ParentTableRelations for the GridTableViews (along with their MasterKeyField and DetailKeyField attributes) and DataKeyNames for the MasterTableView/GridTableViews in the code behind of the page.
  5. Assign data sources (through the DataSourceID attribute) for each table in the grid hierarchy.
    If you do not want to use declarative relations, generate the data in the NeedDataSource/DetailTableDataBind handlers of the grid. On DetailTableDataBind you can determine which data source should be related to the currently bound GridTableView by checking its DataSourceID property (under .NET 2.0).
    Here the DataMember property must have unique value for each detail table (this value has to be defined previously by the developer) and the DataSourceID is the ID of the DataSource control responsible for the corresponding detail table content generation.

Here is a complete source code sample:

VB.NET Copy Code
Private Sub DefineGridStructure()
            Dim RadGrid1 As RadGrid = New RadGrid
            RadGrid1.DataSourceID = "AccessDataSource1"
            RadGrid1.MasterTableView.DataKeyNames = New String() {"CustomerID"}
            RadGrid1.Skin = "Default"
            RadGrid1.Width = Unit.Percentage(100)
            RadGrid1.PageSize = 5
            RadGrid1.AllowPaging = True
            RadGrid1.AutoGenerateColumns = False
            'Master table - Customers (I in hierarchy level)
            RadGrid1.MasterTableView.PageSize = 15
            'Add columnsn
            Dim boundColumn As GridBoundColumn
            boundColumn = New GridBoundColumn
            boundColumn.DataField = "CustomerID"
            boundColumn.HeaderText = "CustomerID"
            RadGrid1.MasterTableView.Columns.Add(boundColumn)
            boundColumn = New GridBoundColumn
            boundColumn.DataField = "ContactName"
            boundColumn.HeaderText = "Contact Name"
            RadGrid1.MasterTableView.Columns.Add(boundColumn)

            'Detail table - Orders (II in hierarchy level)
            Dim tableViewOrders As New GridTableView(RadGrid1)
            tableViewOrders.DataSourceID = "AccessDataSource2"
            tableViewOrders.DataKeyNames = New String() {"OrderID"}
            Dim relationFields As GridRelationFields = New GridRelationFields()
            relationFields.MasterKeyField = "CustomerID"
            relationFields.DetailKeyField = "CustomerID"
            tableViewOrders.ParentTableRelation.Add(relationFields)
            RadGrid1.MasterTableView.DetailTables.Add(tableViewOrders)
            'Add columns
            boundColumn = New GridBoundColumn
            boundColumn.DataField = "OrderID"
            boundColumn.HeaderText = "OrderID"
            tableViewOrders.Columns.Add(boundColumn)
            boundColumn = New GridBoundColumn
            boundColumn.DataField = "OrderDate"
            boundColumn.HeaderText = "Date Ordered"
            tableViewOrders.Columns.Add(boundColumn)
            'Detail table Order-Details (III in hierarchy level)
            Dim tableViewOrderDetails As New GridTableView(RadGrid1)
            tableViewOrderDetails.DataSourceID = "AccessDataSource3"
            tableViewOrderDetails.DataKeyNames = New String() {"OrderID"}
            Dim relationFields2 As GridRelationFields = New GridRelationFields()
            relationFields2.MasterKeyField = "OrderID"
            relationFields2.DetailKeyField = "OrderID"
            tableViewOrderDetails.ParentTableRelation.Add(relationFields2)
            tableViewOrders.DetailTables.Add(tableViewOrderDetails)
            boundColumn = New GridBoundColumn
            boundColumn.DataField = "UnitPrice"
            boundColumn.HeaderText = "Unit Price"
            tableViewOrderDetails.Columns.Add(boundColumn)
            boundColumn = New GridBoundColumn
            boundColumn.DataField = "Quantity"
            boundColumn.HeaderText = "Quantity"
            tableViewOrderDetails.Columns.Add(boundColumn)
            'Add the RadGrid instance to the controls
            Me.PlaceHolder1.Controls.Add(RadGrid1)
End Sub
Private Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Init
            DefineGridStructure()
End Sub
C# Copy Code
private void DefineGridStructure()
{
           RadGrid RadGrid1 =
new RadGrid();
           RadGrid1.DataSourceID =
"AccessDataSource1";
           RadGrid1.MasterTableView.DataKeyNames =
new string[] { "CustomerID" };
           RadGrid1.Skin =
"Default";
           RadGrid1.Width = Unit.Percentage(100);
           RadGrid1.PageSize = 5;
           RadGrid1.AllowPaging = true;
           RadGrid1.AutoGenerateColumns = false;
           RadGrid1.MasterTableView.PageSize = 15;
           
//Add columns
           
GridBoundColumn boundColumn;
           boundColumn =
new GridBoundColumn();
           boundColumn.DataField =
"CustomerID";
           boundColumn.HeaderText =
"CustomerID";
           RadGrid1.MasterTableView.Columns.Add(boundColumn);
           boundColumn =
new GridBoundColumn();
           boundColumn.DataField =
"ContactName";
           boundColumn.HeaderText =
"Contact Name";
           RadGrid1.MasterTableView.Columns.Add(boundColumn);

           
//Detail table - Orders (II in hierarchy level)
           
GridTableView tableViewOrders = new GridTableView(RadGrid1);
           tableViewOrders.DataSourceID =
"AccessDataSource2";
           tableViewOrders.DataKeyNames =
new string[] { "OrderID" };
           GridRelationFields relationFields =
new GridRelationFields();
           relationFields.MasterKeyField =
"CustomerID";
           relationFields.DetailKeyField =
"CustomerID";
           tableViewOrders.ParentTableRelation.Add(relationFields);
           RadGrid1.MasterTableView.DetailTables.Add(tableViewOrders);
           
//Add columns
           
boundColumn = new GridBoundColumn();
           boundColumn.DataField =
"OrderID";
           boundColumn.HeaderText =
"OrderID";
           tableViewOrders.Columns.Add(boundColumn);
           boundColumn =
new GridBoundColumn();
           boundColumn.DataField =
"OrderDate";
           boundColumn.HeaderText =
"Date Ordered";
           tableViewOrders.Columns.Add(boundColumn);
           
//Detail table Order-Details (III in hierarchy level)
           
GridTableView tableViewOrderDetails = new GridTableView(RadGrid1);
           tableViewOrderDetails.DataSourceID =
"AccessDataSource3";
           tableViewOrders.DataKeyNames =
new string[] { "OrderID" };
           GridRelationFields relationFields2 =
new GridRelationFields();
           relationFields2.MasterKeyField =
"OrderID";
           relationFields2.DetailKeyField =
"OrderID";
           tableViewOrderDetails.ParentTableRelation.Add(relationFields2);
           tableViewOrders.DetailTables.Add(tableViewOrderDetails);
           boundColumn =
new GridBoundColumn();
           boundColumn.DataField =
"UnitPrice";
           boundColumn.HeaderText =
"Unit Price";
           tableViewOrderDetails.Columns.Add(boundColumn);
           boundColumn =
new GridBoundColumn();
           boundColumn.DataField =
"Quantity";
           boundColumn.HeaderText =
"Quantity";
           tableViewOrderDetails.Columns.Add(boundColumn);
           
//Add the RadGrid instance to the controls
           
this.PlaceHolder1.Controls.Add( RadGrid1 );
}
protected void Page_Init(object source, System.EventArgs e)
{
           DefineGridStructure();
}
        

 To view online demos presenting how to generate hierarchical grid in reality please follow the links below:

.NET 2.x demo

.NET 1.x demo

 

Creating ItemTemplate/EditItemTemplate of GridTemplateColumn programmatically

You need to design your custom class (holding the set of controls for the ItemTemplate/EditItemTemplate) which implements the ITemplate interface. Then you can assign an instance of this class to the ItemTemplate/EditTemplateTemplate of the corresponding GridTemplateColumn.
 
The example below shows how to embed MS RadioButton for ItemTemplate of GridTemplateColumn at runtime:

ASPX/ASCX Copy Code
<form id="Form1" method="post" runat="server">
  
<asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>
</
form>
        

And in the code-behind:

C# Copy Code
public partial class _Default : System.Web.UI.Page
{
   
protected RadGrid grid;
   
override protected void OnInit(EventArgs e)
   {
       DefineGridStructure();
       
base.OnInit(e);
   }
   
private void DefineGridStructure()
   {
       
this.grid = new RadGrid();
       
this.grid.AutoGenerateColumns = false;
       
this.grid.DataSourceID = "SqlDataSource1";

       
//other columns definitions ----------------------------

        
string templateColumnName = "ContactName";
       GridTemplateColumn templateColumn =
new GridTemplateColumn();
       templateColumn.ItemTemplate =
new MyTemplate(templateColumnName);
       templateColumn.HeaderText = templateColumnName;

       GridBoundColumn boundColumn1 =
new GridBoundColumn();
       boundColumn1.DataField =
"ContactName";
       boundColumn1.UniqueName =
"ConactName";
       boundColumn1.HeaderText =
"Bound Column";
       
this.grid.MasterTableView.Columns.Add(templateColumn);
       
this.grid.MasterTableView.Columns.Add(boundColumn1);
       grid.AllowPaging = true;
       grid.PageSize = 5;
       
this.PlaceHolder1.Controls.Add(grid);
   }
   
protected void Page_Load(object sender, EventArgs e)
   {
   }
private class MyTemplate : ITemplate
   {
       
protected LiteralControl lControl;
       
protected RequiredFieldValidator validatorTextBox;
       
protected HyperLink searchGoogle;
       
protected TextBox textBox;
       
protected CheckBox boolValue;

        
private string colname;

        
public MyTemplate(string cName)
       {
           colname = cName;
       }

 
public void InstantiateIn(System.Web.UI.Control container)
       {
           lControl =
new LiteralControl();
           lControl.ID =
"lControl";
           lControl.DataBinding +=
new EventHandler(lControl_DataBinding);

           textBox =
new TextBox();
           textBox.ID =
"templateColumnTextBox";

           validatorTextBox =
new RequiredFieldValidator();
           validatorTextBox.ControlToValidate =
"templateColumnTextBox";
           validatorTextBox.ErrorMessage =
"*";

           searchGoogle =
new HyperLink();
           searchGoogle.ID =
"searchGoogle";
           searchGoogle.DataBinding +=
new EventHandler(searchGoogle_DataBinding);

           boolValue =
new CheckBox();
           boolValue.ID =
"boolValue";
           boolValue.DataBinding +=
new EventHandler(boolValue_DataBinding);
           boolValue.Enabled = false;

           Table table =
new Table();
           TableRow row1 =
new TableRow();
           TableRow row2 =
new TableRow();

           TableCell cell11 =
new TableCell();
           TableCell cell12 =
new TableCell();
           TableCell cell21 =
new TableCell();
           TableCell cell22 =
new TableCell();
           row1.Cells.Add(cell11);
           row1.Cells.Add(cell12);
           row2.Cells.Add(cell21);
           row2.Cells.Add(cell22);
           table.Rows.Add(row1);
           table.Rows.Add(row2);

           cell11.Text = colname +
": ";
           cell12.Controls.Add(lControl);
           cell21.Text =
"Search Google for: ";
           cell22.Controls.Add(searchGoogle);

           container.Controls.Add(textBox);
           container.Controls.Add(validatorTextBox);
           container.Controls.Add(table);
           container.Controls.Add(
new LiteralControl("<br />"));
           container.Controls.Add(boolValue);


       }

       
void boolValue_DataBinding(object sender, EventArgs e)
       {
           CheckBox cBox = (CheckBox)sender;
           GridDataItem container = (GridDataItem)cBox.NamingContainer;
           cBox.Checked = (
bool)((DataRowView)container.DataItem)[ "Bool"];
       }

       
void searchGoogle_DataBinding(object sender, EventArgs e)
       {

           HyperLink link = (HyperLink)sender;
           GridDataItem container = (GridDataItem)link.NamingContainer;
           link.Text = ((DataRowView)container.DataItem)[colname].ToString();
           link.NavigateUrl =
"http://www.google.com/search?hl=en&q=" + ((DataRowView)container.DataItem)["ContactName"].ToString() + "&btnG=Google+Search";
       }

        
public void lControl_DataBinding(object sender, EventArgs e)
       {
           LiteralControl l = (LiteralControl)sender;
           GridDataItem container = (GridDataItem)l.NamingContainer;
           l.Text = ((DataRowView)container.DataItem)[colname].ToString() +
"<br />";


       }
   }
}
            

 
VB.NET Copy Code
Public Class _Default
    Inherits System.Web.UI.Page

    Protected grid As RadGrid

    Protected Overrides Sub OnInit(ByVal e As EventArgs)
        DefineGridStructure
        MyBase.OnInit(e)
    End Sub

    Private Sub DefineGridStructure()
         Me.grid = New RadGrid
         Me.grid.AutoGenerateColumns = false
         Me.grid.DataSourceID = "SqlDataSource1"
         'other columns definitions ----------------------------
         Dim templateColumnName As String = "ContactName"
         Dim templateColumn As GridTemplateColumn = New GridTemplateColumn
        templateColumn.ItemTemplate = New MyTemplate(templateColumnName)
        templateColumn.HeaderText = templateColumnName
         Dim boundColumn1 As GridBoundColumn = New GridBoundColumn
        boundColumn1.DataField = "ContactName"
        boundColumn1.UniqueName = "ConactName"
        boundColumn1.HeaderText = "Bound Column"
         Me.grid.MasterTableView.Columns.Add(templateColumn)
         Me.grid.MasterTableView.Columns.Add(boundColumn1)
        grid.AllowPaging = true
        grid.PageSize = 5
         Me.PlaceHolder1.Controls.Add(grid)
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    End Sub

    Private Class MyTemplate
        Implements ITemplate

        Protected lControl As LiteralControl

        Protected validatorTextBox As RequiredFieldValidator

        Protected searchGoogle As HyperLink

        Protected textBox As TextBox

        Protected boolValue As CheckBox

         Private colname As String

         Public Sub New(ByVal cName As String)
            MyBase. New
            colname = cName
         End Sub

         Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements ITemplate.InstantiateIn
            lControl = New LiteralControl
            lControl.ID = "lControl"
            AddHandler lControl.DataBinding, AddressOf Me.lControl_DataBinding
            textBox = New TextBox
            textBox.ID = "templateColumnTextBox"
            validatorTextBox = New RequiredFieldValidator
            validatorTextBox.ControlToValidate = "templateColumnTextBox"
            validatorTextBox.ErrorMessage = "*"
            searchGoogle = New HyperLink
            searchGoogle.ID = "searchGoogle"
            AddHandler searchGoogle.DataBinding, AddressOf Me.searchGoogle_DataBinding
            boolValue = New CheckBox
            boolValue.ID = "boolValue"
            AddHandler boolValue.DataBinding, AddressOf Me.boolValue_DataBinding
            boolValue.Enabled = false
             Dim table As Table = New Table
             Dim row1 As TableRow = New TableRow
             Dim row2 As TableRow = New TableRow
             Dim cell11 As TableCell = New TableCell
             Dim cell12 As TableCell = New TableCell
             Dim cell21 As TableCell = New TableCell
             Dim cell22 As TableCell = New TableCell
            row1.Cells.Add(cell11)
            row1.Cells.Add(cell12)
            row2.Cells.Add(cell21)
            row2.Cells.Add(cell22)
            table.Rows.Add(row1)
            table.Rows.Add(row2)
            cell11.Text = (colname + ": ")
            cell12.Controls.Add(lControl)
            cell21.Text = "Search Google for: "
            cell22.Controls.Add(searchGoogle)
            container.Controls.Add(textBox)
            container.Controls.Add(validatorTextBox)
            container.Controls.Add(table)
            container.Controls.Add( New LiteralControl("<br />"))
            container.Controls.Add(boolValue)
         End Sub

         Private Sub boolValue_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
             Dim cBox As CheckBox = CType(sender,CheckBox)
             Dim container As GridDataItem = CType(cBox.NamingContainer,GridDataItem)
            cBox.Checked = CType(CType(container.DataItem,DataRowView)( "Bool"),Boolean)
         End Sub

         Private Sub searchGoogle_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
             Dim link As HyperLink = CType(sender,HyperLink)
             Dim container As GridDataItem = CType(link.NamingContainer,GridDataItem)
            link.Text = CType(container.DataItem,DataRowView)(colname).ToString
            ( "http://www.google.com/search?hl=en&q=" _
                        + (CType(container.DataItem,DataRowView)("ContactName").ToString + btnG)) = (Google + Search)
            link.NavigateUrl = (Google + Search)
             ""
         End Sub

         Public Sub lControl_DataBinding(ByVal sender As Object, ByVal e As EventArgs)
             Dim l As LiteralControl = CType(sender,LiteralControl)
             Dim container As GridDataItem = CType(l.NamingContainer,GridDataItem)
            l.Text = (CType(container.DataItem,DataRowView)(colname).ToString + "<br />")
         End Sub
    End Class
End Class

The code above will result in:

Creating Templates programmatically

Detailed information about how to create templates programmatically you can find in the MSDN:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vbtchcreatingwebservercontroltemplatesprogrammatically.asp