RadGrid for ASP.NET AJAX

RadControls Send comments on this topic.
Command item template
See Also
Controls > RadGrid > Insert/Update/Delete records > CommandItem > Command item template

Glossary Item Box

In order to show the command item, you should set CommandItemDisplay property of GridTableView. It can take four values: None, Top, Bottom, TopAndBottom corresponding to the place where it will appear. The command item content can be customized using the template of a GridTableView.CommandItemTemplate.

ASPX/ASCX Copy Code
<CommandItemTemplate>
Custom command item template
<asp:LinkButton Style="vertical-align: bottom" ID="btnEditSelected" runat="server"
  
CommandName= "EditSelected" Visible='<%# RadGrid1.EditIndexes.Count == 0 %>'><img style="border:0px" alt="" src="../../DataEditing/Img/Edit.gif" /> Edit Selected Customers</asp:LinkButton>
 
<asp:LinkButton ID="btnUpdateEdited" runat="server" CommandName="UpdateEdited" Visible='<%# RadGrid1.EditIndexes.Count > 0 %>'><img style="border:0px" alt="" src="../../DataEditing/Img/Update.gif" /> Update Customers</asp:LinkButton>

<
asp:LinkButton ID="btnCancel" runat="server" CommandName="CancelAll" Visible='<%# RadGrid1.EditIndexes.Count > 0 || RadGrid1.MasterTableView.IsItemInserted %>'><img style="border:0px" alt="" src="../../DataEditing/Img/Cancel.gif" /> Cancel editing</asp:LinkButton>

 
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="InitInsert" Visible='<%# !RadGrid1.MasterTableView.IsItemInserted %>'><img style="border:0px" alt="" src="../../DataEditing/Img/AddRecord.gif" /> Add new Customer</asp:LinkButton>
 
<asp:LinkButton ID="LinkButton3" runat="server" CommandName="PerformInsert" Visible='<%# RadGrid1.MasterTableView.IsItemInserted %>'><img style="border:0px" alt="" src="../../DataEditing/Img/Insert.gif" /> Add this Customer</asp:LinkButton>

<asp:LinkButton ID="LinkButton1" OnClientClick="javascript:return confirm('Delete all selected customers?')"
    
runat= "server" CommandName="DeleteSelected"><img style="border:0px" alt="" src="../../DataEditing/Img/Delete.gif" /> Delete Selected Customers</asp:LinkButton>

<asp:LinkButton ID="LinkButton4" runat="server" CommandName="Re bindGrid"><img style="border:0px" alt="" src="../../DataEditing/Img/Refresh.gif" /> Refresh customer list</asp:LinkButton>
<br/>
</
CommandItemTemplate>

This code will result in:

CommandItemTemplate

 

In the CommandItemTemplate you can add any type of buttons that rise command event and Telerik RadGrid will fire the ItemCommandEvent (see below) on the server when this button is clicked.

For example:

 

ASPX/ASCX Copy Code
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="InitInsert">Add New</asp:LinkButton>

 

will automatically set Telerik RadGrid in "Insert" mode as the "InitInsert" command is processed internally by Telerik RadGrid. You can also fetch the command in ItemCommandEvent checking the value of the event argument CommandName for the value of "InitInsert" (corresponding to the value of the static member RadGrid.InitInsertCommandName).

Handling custom commands - Delete command (CommandItem example)

Generally you can handle any command, using the ItemCommandEvent. The example below shows hot to handle a custom command "DeleteSelected". It will delete all selected Items. In the ASPX file, we set the CommandName property to "DeleteSelected". Then in the ItemCommandEvent handler, we check if the CommandName was "DeleteSelected" and call the PerformDelete method, which will delete all selected items. Note that you will need to set AllowAutomaticDeletes property to true.

ASPX/ASCX Copy Code
 <CommandItemTemplate>
     
<asp:LinkButton ID="LinkButton1" OnClientClick="javascript:return confirm('Delete all selected customers?')"
                       
runat= "server" CommandName="DeleteSelected"><img style="border:0px" alt="" src="../../DataEditing/Img/Delete.gif" /> Delete Selected Custoemrs</asp:LinkButton>

 
</CommandItemTemplate>

Codebehind:   

C# Copy Code
 protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
 {
 ....

   
if (e.CommandName == "DeleteSelected")
     {
       
if (RadGrid1.SelectedIndexes.Count == 0)
       {
         
return;
       }

       
foreach (GridDataItem item in RadGrid1.SelectedItems)
       {
         e.Item.OwnerTableView.PerformDelete(item, true);
       }

       e.Item.OwnerTableView.Rebind();
       
return;
     }
     ....
 }
VB.NET Copy Code
Protected Sub RadGrid1_ItemCommand(ByVal source As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.ItemCommand
   If e.CommandName = "DeleteSelected" Then

        If RadGrid1.SelectedIndexes.Count = 0 Then
           Return
        End If

        For Each item As GridDataItem In RadGrid1.SelectedItems
           e.Item.OwnerTableView.PerformDelete(item, True)
        Next
       e.Item.OwnerTableView.Rebind()
        Return
    End If
End Sub


How to customize the Add new record/Refresh text in the CommandItem area

The means to achieve your goal is using CommandItemTemplate:

ASPX/ASCX Copy Code
<telerik:radgrid id="RadGrid1" runat="server">
<MasterTableView CommandItemDisplay="Top">
   
<CommandItemTemplate>
     
<asp:Button ID="Button1" Text="Add new item"
      
Runat="server" CommandName="InitInsert"></asp:Button>
   
</CommandItemTemplate>
</MasterTableView>
</
telerik:radgrid>
Also,

if you have two buttons, you can place the buttons in a HTML table embedded inside the CommandItemTemplate. Here is a sample structure:

ASPX/ASCX Copy Code
<CommandItemTemplate>
 
<table>
  
<tr>
<td width="30%">
 
<asp:LinkButton ID="btnAdd"
  
Text="Add new item" CommandName="InitInsert" Runat="server"></asp:LinkButton>
</td>
<td width="40%">
</td>
<td width="30%">
 
<asp:LinkButton ID="btnRefresh" Text="Refresh data"
  
CommandName="Rebind" Runat="server"></asp:LinkButton>
</td>
  
</tr>
 
</table>
</
CommandItemTemplate>


Setting preferences for controls inside the CommandItemTemplate at runtime


There are cases in which you may want to access the controls inside your CommandItemTemplate from the code-behind and dynamically change their preferences (in par with some particular restrictions/certain conditions). Here are the steps you can perform to reference controls inside the CommandItemTemplate programmatically:

  1. Subscribe to the ItemCreated event of Telerik RadGrid
  2. Check whether the currently bound item is GridCommandItem
  3. Locate the respective control using the FindControl method of the command item
  4. Change its attributes according to your needs

In the example below we change the Text and CommandName properties for MS LinkButton inside the CommandItemTemplate object:


ASPX/ASCX Copy Code
<telerik:RadGrid ID="RadGrid1" DataSourceID="AccessDataSource1" runat="server" OnItemCreated="RadGrid1_ItemCreated">
           
<MasterTableView Width="100%" CssClass="MasterTable" DataSourceID="AccessDataSource1" CommandItemDisplay="Top" >
                
<CommandItemTemplate>
                   
<asp:LinkButton ID="LinkButton1" runat="server">Default Text</asp:LinkButton>
               
</CommandItemTemplate>
           
</MasterTableView>
       
</telerik:RadGrid>
       
<br />
<
asp:AccessDataSource ID="AccessDataSource1" DataFile="~/Grid/Data/Access/Nwind.mdb"
SelectCommand="SELECT TOP 10 CustomerID, CompanyName, ContactName, ContactTitle, Address, PostalCode FROM Customers"
runat="server"></asp:AccessDataSource>

And in the code-behind:

C# Copy Code
protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
{
        
if (e.Item is GridCommandItem)
       {
           GridCommandItem commandItem = e.Item
as GridCommandItem;
           LinkButton button = commandItem.FindControl(
"LinkButton1")as LinkButton;

           button.CommandName =
"MyCommandName";
           button.Text =
"Perform custom operation";
       }
}
VB.NET Copy Code
Protected Sub RadGrid1_ItemCreated(sender As Object, e As GridItemEventArgs)

   If TypeOf e.Item Is GridCommandItem Then

      Dim commandItem As GridCommandItem = Ctype(e.Item, GridCommandItem)
      Dim button As LinkButton = CType(commandItem.FindControl("LinkButton1"), LinkButton)

      button.CommandName = "MyCommandName"
      button.Text = "Perform custom operation"
   End If
End Sub 'RadGrid1_ItemCreated

Display different controls in CommandItemTemplate with CommandItemDisplay = "TopAndBottom"

There are cases in which you may want to display different controls inside the top/bottom command item when choosing the CommandItemDisplay="TopAndBottom" option. This is attainable by switching the visibility of the controls on ItemCreated. Note that you can determine whether the command item will be displayed in the header/footer of the grid by checking the NamingContainer for the GridCommandItem object (it will be GridTHead for the header and GridTFoot for the footer).
The code snippets below illustrate a sample implementation:

ASPX/ASCX Copy Code
<telerik:RadGrid id="RadGrid1" runat="server" Skin="Ice" AllowSorting="true" AllowMultiRowSelection="true" AllowMultiRowEdit="true">
   
<MasterTableView CommandItemDisplay="TopAndBottom">
    
<CommandItemTemplate>
     
<table>
      
<tr>
       
<td width="30%">
        
<asp:LinkButton ID="btnAdd" Text="Add new item" CommandName="InitInsert" Runat="server"></asp:LinkButton>
        
<asp:LinkButton ID="btnEdit" Text="Edit selected" CommandName="EditSelected" Runat="server"></asp:LinkButton>
       
</td>
       
<td width="40%">
       
</td>
       
<td width="30%">
        
<asp:LinkButton ID="btnRefresh" Text="Refresh data" CommandName="Rebind" Runat="server"></asp:LinkButton>
        
<asp:LinkButton ID="btnUpdate" Text="Update edited" CommandName="UpdateEdited" Runat="server"></asp:LinkButton>
       
</td>
      
</tr>
     
</table>
    
</CommandItemTemplate>
   
</MasterTableView>
   
<ClientSettings>
    
<Selecting AllowRowSelect="true" />
   
</ClientSettings>
</
telerik:RadGrid>
VB.NET Copy Code
Private Sub RadGrid1_ItemCreated(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles RadGrid1.ItemCreated
        If (TypeOf e.Item Is GridCommandItem) Then
            Dim commandItem As GridCommandItem = CType(e.Item, GridCommandItem)

            If (TypeOf commandItem.NamingContainer Is GridTHead) Then
                commandItem.FindControl("btnEdit").Visible = False
                commandItem.FindControl("btnUpdate").Visible = False

            ElseIf (TypeOf commandItem.NamingContainer Is GridTFoot) Then

                commandItem.FindControl("btnAdd").Visible = False
                commandItem.FindControl("btnRefresh").Visible = False
            End If
        End If
End Sub
C# Copy Code
private void RadGrid1_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if (e.Item is GridCommandItem)
{
  GridCommandItem commandItem = (GridCommandItem)e.Item;

  
if (commandItem.NamingContainer is GridTHead)
  {
    commandItem.FindControl(
"btnEdit").Visible = false;
    commandItem.FindControl(
"btnUpdate").Visible = false;
  }
  
else if (commandItem.NamingContainer is GridTFoot)
  {
    commandItem.FindControl(
"btnAdd").Visible = false;
    commandItem.FindControl(
"btnRefresh").Visible = false;
  }
}
}


Define CommandItemTemplate programmatically

You need to design your custom class (holding the set of controls for the CommandItemTemplate) which implements the ITemplate interface. Then you can assign an instance of this class to the CommandItemTemplate of the corresponding GridTableView.
 
The example below shows how to embed MS LinkButtons (for add record and refresh) in CommandItemTemplate of the MasterTableView at runtime:

C# Copy Code
using Telerik.Web.UI;
using System.Web.UI;

protected RadGrid RadGrid1;


private class MyCommandItemTemplate : ITemplate
{

   
protected LinkButton addButton;

   
protected LinkButton refreshButton;

   
public MyCommandItemTemplate()
   {
   }

   
public void InstantiateIn(System.Web.UI.Control container)
   {
       addButton =
new LinkButton();
       addButton.ID =
"addButton";
       addButton.Text =
"Add record";
       addButton.CommandName =
"InitInsert";

       refreshButton =
new LinkButton();
       refreshButton.ID =
"refreshButton";
       refreshButton.Text =
"Refresh grid";
       refreshButton.CommandName =
"Rebind";

       container.Controls.Add(addButton);
       container.Controls.Add(
new LiteralControl("      "));
       container.Controls.Add(refreshButton);
   }
}


   
protected override void OnInit(EventArgs e)
   {
       InitializeComponent;
       DefineGridStructure();
       
base.OnInit(e);
   }

   
private void DefineGridStructure()
   {
       
this.RadGrid1 = new RadGrid();
       
this.RadGrid1.AutoGenerateColumns = false;
       
this.RadGrid1.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Top;

       RadGrid1.NeedDataSource +=
new System.EventHandler(this.RadGrid1_NeedDataSource);

       RadGrid1.MasterTableView.CommandItemTemplate =
new MyCommandItemTemplate();
        
// runtime column definitions
   }
VB.NET Copy Code
Imports Telerik.Web.UI
Imports System.Web.UI

Protected WithEvents RadGrid1 as RadGrid

Private Class MyCommandItemTemplate
         Implements ITemplate

        Protected addButton As LinkButton
        Protected refreshButton As LinkButton

         Public Sub New()
            MyBase. New()

         End Sub

         Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
            addButton = New LinkButton
            addButton.ID = "addButton"
            addButton.Text = "Add record"
            addButton.CommandName = "InitInsert"

            refreshButton = New LinkButton
            refreshButton.ID = "refreshButton"
            refreshButton.Text = "Refresh grid"
            refreshButton.CommandName = "Rebind"

            container.Controls.Add(addButton)
            container.Controls.Add( New LiteralControl(" "))
            container.Controls.Add(refreshButton)
         End Sub
End Class

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

Private Sub DefineGridStructure()
          Me.RadGrid1 = New RadGrid
          Me.RadGrid1.AutoGenerateColumns = false
          Me.RadGrid1.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Top

        AddHandler RadGrid1.NeedDataSource, AddressOf Me.RadGrid1_NeedDataSource

        RadGrid1.MasterTableView.CommandItemTemplate = New MyCommandItemTemplate()
           'runtime column definitions
End Sub

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

See Also