Products
Services
Contact Us

Scripts: C# :: Telerik Web Controls :: Library Article #15

Developer's Section

Creating a Custom Template Edit Form Inside an Ajaxified Telerik Radgrid
By: Erobo Team Member

Hire a Developer for Related Work / Installation | $55 hr
Rating:  | Rate It:   
Average Votes: (1973)
Favorites:

Article teaches you the basics of creating a custom template inside a Telerik Radgrid that has been Ajaxified.

One of the benefits of creating a form template inside an ajaxified Radgrid is that you can place the elements of the form in any way you want. One of the requirements is to declare the insert and update buttons inside the form template to handle the Radgrid method calls explicitly. E.g. Like the performInsert command and update command. In the following example we demostrate the use of them. In Code Snippet 1 (Designer View) you will see the declaration of the custom edit form template which contains an input box, a dropdown and a few check boxes. In the code behind you will see the appropiate handling including assigning the datasource programmatically to the Radgrid.

Code for Designer View (CarRegistration.aspx):

 Code Snippet 1

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CarRegistration.aspx.cs" 
Inherits="Dev.Admin.CarRegistration" %>
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" 
TagPrefix="telerik" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title>Edit Car Registration</title>
</head>
<body>
  <form id="form1" runat="server">
  <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
  </telerik:RadScriptManager>
  <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
  </telerik:RadAjaxManager>
  <div> 
  <table id="Table1" runat="server" width="100%" cellpadding="0" cellspacing="0">
    <tr>
      <td>
        <table>
          <tr>
            <td width="500">
              <h2>Car Registration Admin</h2>
            </td>
            <td align="right">
              <asp:LinkButton ID="btnAdd2" runat="server" OnClick="Button3_Click" 
              Text="Add New Progress Code" Visible="true" style="margin-top:-3px;color:White;" 
              class="button_orange"> </asp:LinkButton>   
            </td>
          </tr>
        </table>
      </td>
    </tr>
    <tr>
      <td style="padding-bottom: 12px">
      <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel2" runat="server" 
      InitialDelayTime="3" MinDisplayTime="3" Skin="Default" />
      <telerik:RadGrid runat="server" ID="RadGrid1" AutoGenerateColumns="False" 
      Width="100%"
      ShowStatusBar="True" GridLines="None" OnItemDataBound="RadGrid1_ItemCreated"
      OnInsertCommand="RadGrid1_InsertCommand" 
      OnDeleteCommand="RadGrid1_DeleteCommand"
      OnNeedDataSource="RadGrid_NeedDataSource"
      AllowPaging="true" OnUpdateCommand="RadGrid1_UpdateCommand" PageSize="10" 
      OnItemCommand="RadGrid1_ItemCommand"
      ShowHeader="true" Visible="true" AllowAutomaticUpdates="true">
      <PagerStyle Mode="NumericPages" AlwaysVisible="true" />
      <MasterTableView CommandItemDisplay="Top" DataKeyNames="carRegistrationId">
      <CommandItemTemplate>
        <div style="display: none;background-color:White;text-align:left;">
        <asp:LinkButton ID="btnAdd" runat="server" CommandName="InitInsert"
        Text="Add New Car Registration" 
        Visible="true" class="btngrid_action">
        </asp:LinkButton>    
        <asp:LinkButton ID="LinkButton1" runat="server" CommandName="PerformInsert" 
        Text="INSERT" Visible="false">
        </asp:LinkButton>    
        </div>
      </CommandItemTemplate>
      <EditFormSettings EditFormType="Template">
        <FormTemplate>
          <!--Start Form Template-->
          <table border="0" cellpadding="2" cellspacing="2" width="100%" 
          style="background-color:White">
          <tr>
            <td valign="top" width="140"> </td>
            <td valign="top" align="left" > </td>
          </tr>
          <tr>
            <td valign="top">Car Tag:</td>
            <td valign="top" align="left">
            <asp:TextBox id="tag_number" runat="server" ></asp:TextBox>
            </td>
          </tr>
          <tr>
            <td valign="top">Type:</td>
            <td valign="top" align="left">
            <asp:DropDownList id="carType" runat="server" >
            <asp:ListItem value="1" >Compact</asp:ListItem>
            <asp:ListItem value="2" >Mid-size</asp:ListItem>
            <asp:ListItem value="3" >SUV</asp:ListItem>
            </asp:DropDownList>
            </td>
          </tr>
          <tr>
          <tr>
            <td>Send Registration Notice:
            <i>Check all that apply.</i>
            </td>
            <td>
              <table>
              <tr>
                <td class="text">By mail</td><td class="text">By e-mail</td>
              </tr>
              <tr>
                <td><asp:CheckBox runat="server" id="send_mail" /></td>
                <td><asp:CheckBox runat="server" id="send_email" /></td>
              </tr>
              </table>
            </td>
          </tr>
          </table>
          <br />
          <br />
          <!-- Hanlde RadGrid Calls Manually-->
         <asp:LinkButton ID="btnUpdate" runat="server" CausesValidation="true" Text="Insert" />
         <asp:LinkButton ID="btnCancel" CommandName="Cancel" CausesValidation="false" 
         Text="Cancel" runat="server" />
       <!--End Form Template-->
       </FormTemplate>
     </EditFormSettings>
     <Columns>
     <telerik:GridBoundColumn DataField="carRegistrationId" UniqueName="carRegistrationId"
      HeaderText="reg ID" ReadOnly="True" Visible="true" />
     <telerik:GridTemplateColumn HeaderText="Tag Number" UniqueName="TagNumber" 
     SortExpression="TagNumber">
       <ItemTemplate>
         <asp:Label runat="server" ID="lblTagNumber" Text='<%# Eval("TagNumber") %>' />
       </ItemTemplate>
     <HeaderStyle Width="30%" />
     </telerik:GridTemplateColumn>
     <telerik:GridTemplateColumn HeaderText="Car Type" UniqueName="carType">
       <ItemTemplate>
         <asp:Label runat="server" ID="carType" 
           Text='<%# getType(Convert.ToString(Eval("carType"))) %>' />
       </ItemTemplate>
     </telerik:GridTemplateColumn>
     <telerik:GridTemplateColumn HeaderText="Last Modified By" UniqueName="RegModBy" 
      SortExpression="UserName">
       <ItemTemplate>
         <asp:Label runat="server" ID="lblModifiedBy" Text='' />
       </ItemTemplate>
     </telerik:GridTemplateColumn>
     <telerik:GridTemplateColumn HeaderText="Last Modified On" UniqueName="RegModOn">
       <ItemTemplate>
         <asp:Label runat="server" ID="lblModifiedOn" Text='<%# Eval("RegLastmodon") %>' />
       </ItemTemplate>
     </telerik:GridTemplateColumn>
     <telerik:GridButtonColumn ButtonType="ImageButton" UniqueName="reg_edit" 
     ItemStyle-HorizontalAlign="Right" runat="server" CommandName="Edit">
     <HeaderStyle Width="20" />
     </telerik:GridButtonColumn>
     <telerik:GridButtonColumn Text="Delete" CommandName="Delete" 
     ButtonType="ImageButton" 
     ConfirmDialogType="RadWindow" ConfirmText="Are you sure you 
     want to delete this registration?">
     <HeaderStyle Width="2%" />
     </telerik:GridButtonColumn>
     </Columns>
     <PagerStyle AlwaysVisible="True" />
     <NoRecordsTemplate>
     <div>There are no records to display</div>
     </NoRecordsTemplate>
     </MasterTableView>
     </telerik:RadGrid>
     </td>
    </tr>
  </table>
  </div>
  </form>
</body>
</html>


Code Behind View (CarRegistration.aspx.cs):

 Code Snippet 2

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

namespace Dev.Admin
{

  public partial class GloablProgressCodes : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      var manager = RadAjaxManager.GetCurrent(Page);
      //Ajaxify Grid
      manager.AjaxSettings.AddAjaxSetting(RadGrid1, RadGrid1, RadAjaxLoadingPanel2);
      //Ajaxify Button to Trigger Add
      manager.AjaxSettings.AddAjaxSetting(btnAdd2, RadGrid1, RadAjaxLoadingPanel2);

      //Assign Data Source Programmatically
      if (!Page.IsPostBack) {
        CarRegService thisServ = new CarRegService();
        TList<CarReg> thisL = thisServ.Find(" reg = 'vehicle' ");
        RadGrid1.DataSource = thisL;
        ViewState["carRegSource"] = thisL.ToArray();
      }
    }
    
    //Assign On Need DataSource to the RadGrid
    protected void RadGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
      if (ViewState["carRegSource"] != null)
      {
        CarReg[] newArray = (CarReg[])ViewState["carRegSource"];

        TList<CarReg> thisTList = new TList<CarReg>(newArray);

        RadGrid1.DataSource = thisTList;
      }
    }

    public string getType(string thisType)
    {
      if (thisType != null)
      {
        return (thisType == "1")? "Compact" : (thisType == "2")? Mid-Size : SUV;
      }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
      RadGrid1.MasterTableView.IsItemInserted = true;
      RadGrid1.Rebind();
    }

    protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
    {
      try
      {
        CarReg CarRegObj = new CarReg();

        GridEditFormInsertItem insertItem = e.Item as GridEditFormInsertItem;
        CarRegObj.TagNumber = (insertItem.FindControl("tag_number") as TextBox).Text;

        DropDownList thisL1 = (DropDownList)insertItem.FindControl("carType");

        if (thisL1.SelectedIndex == 0)
        {
          CarRegObj.carType = "1";
        }
        else if (thisL1.SelectedIndex == 1)
        {
          CarRegObj.carType = "2";
        }
        else
        {
          CarRegObj.carType = "3";
        }

        CheckBox thisC1 = (CheckBox)insertItem.FindControl("send_mail");

        if (thisC1.Checked == true)
        {
          CarRegObj.SendMail = "Y";
        }
        else
        {
          CarRegObj.SendMail = "N";
        }

        CheckBox thisC2 = (CheckBox)insertItem.FindControl("send_email");

        if (thisC2.Checked == true)
        {
          CarRegObj.SendEmail = "Y";
        }
        else
        {
          CarRegObj.SendEmail = "Y";
        }

        CarRegObj.CreatedOn = DateTime.Now;
        CarRegObj.CreatedBy = Convert.ToInt16(user.identity.name);
        CarRegService thisSerrv = new CarRegService();
        thisSerrv.Insert(CarRegObj);
      }
      catch (Exception ex)
      {
        string error = Server.HtmlEncode("Unable to insert Car Tag. Reason: " + 
                       ex.StackTrace).Replace("'", "'").Replace("\r\n", "<br />");
      }


      CarRegService thisServ = new CarRegService();
      TList<CarReg> thisL = thisServ.Find(" reg = 'vehicle' ");
      RadGrid1.DataSource = thisL;
      RadGrid1.Rebind();
      ViewState["carRegSource"] = thisL.ToArray();
    }

    protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
    {

      int thisCcp = Convert.ToInt16("0" + 
      Convert.ToString(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["carRegistrationId"]));


      try
      {
        CarRegService thisSerrv = new CarRegService();

        CarReg newEntityObj = thisSerrv.GetByCarRegId(thisCcp);
        
        GridEditableItem updateItem = e.Item as GridEditableItem;

        CarRegObj.TagNumber = (updateItem.FindControl("tag_number") as TextBox).Text;

        DropDownList thisL1 = (DropDownList)updateItem.FindControl("carType");

        if (thisL1.SelectedIndex == 0)
        {
          CarRegObj.carType = "1";
        }
        else if (thisL1.SelectedIndex == 1)
        {
          CarRegObj.carType = "2";
        }
        else
        {
          CarRegObj.carType = "3";
        }

        CheckBox thisC1 = (CheckBox)updateItem.FindControl("send_mail");

        if (thisC1.Checked == true)
        {
          CarRegObj.SendMail = "Y";
        }
        else
        {
          CarRegObj.SendMail = "N";
        }

        CheckBox thisC2 = (CheckBox)updateItem.FindControl("send_email");

        if (thisC2.Checked == true)
        {
          CarRegObj.SendEmail = "Y";
        }
        else
        {
          CarRegObj.SendEmail = "Y";
        }

        CarRegObj.LastmodifiedBy = Convert.ToInt16(user.identity.name);
        CarRegObj.LogprogressLastmodon = DateTime.Now;
        thisSerrv.Update(CarRegObj);

        CarRegService thisServ = new CarRegService();
        TList<CarReg> thisL = thisServ.Find(" reg = 'vehicle' ");
        RadGrid1.DataSource = thisL;
        RadGrid1.Rebind();
        ViewState["CarRegSource"] = thisL.ToArray();
        updateItem.Edit = false;
      }
      catch (Exception ex)
      {
        string error = Server.HtmlEncode("Unable to Update Car Registration. Reason: " + 
                       ex.StackTrace).Replace("'", "'").Replace("\r\n", "<br />");
      }

    }

    protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
    {

      int thisCcp = Convert.ToInt16("0" + 
      Convert.ToString(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["carRegistrationId"]));


      try
      {
        CarRegService thisSerrv = new CarRegService();
        CarReg newEntityObj = thisSerrv.GetByCarRegId(thisCcp);
        thisSerrv.Delete(newEntityObj);
      }
      catch (Exception ex)
      {
        string error = Server.HtmlEncode("Unable to Delete Car Registration. Reason: " + 
                       ex.StackTrace).Replace("'", "'").Replace("\r\n", "<br />");
      }


      CarRegService thisServ = new CarRegService();
      TList<CarReg> thisL = thisServ.Find(" reg = 'vehicle' ");
      RadGrid1.DataSource = thisL;
      RadGrid1.Rebind();
      ViewState["carRegSource"] = thisL.ToArray();
    }

    protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
    {

    }
    
    //->On item data bound retrieve a rowview of the object and update
    //labels appropriately.
    //->Assign the right command name to the update and insert buttons on edit form template
    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
    {

      if (e.Item.ItemType == GridItemType.Item || 
          e.Item.ItemType == GridItemType.AlternatingItem)
      {

        CarReg rowView = (CarReg)e.Item.DataItem;

        GridDataItem item = (GridDataItem)e.Item;


        if (rowView.LastmodifiedBy > 0)
        {
          USDriversService thisUs = new USDriversService();

          USDrivers thisUser = thisUs.GetById(Convert.ToInt16(rowView.LastmodifiedBy));

          item["ProModBy"].Text = thisUser.Username;
        }
        else
        {
          item["ProModBy"].Text = "Not Known";
        }

      }


      if (e.Item is GridEditFormInsertItem)
      {
        GridEditFormInsertItem editedItem = null;

        editedItem = (GridEditFormInsertItem)e.Item;
        LinkButton btnUpdate1 = (LinkButton)editedItem.FindControl("btnUpdate");
        btnUpdate1.CommandName = "PerformInsert";

      }

      if (e.Item is GridEditableItem && e.Item.ItemIndex > -1 && e.Item.IsInEditMode)
      {
        GridEditableItem editedItem1 = null;

        e.Item.OwnerTableView.IsItemInserted = false;
        editedItem1 = (GridEditableItem)e.Item;
        LinkButton btnUpdate1 = (LinkButton)editedItem1.FindControl("btnUpdate");
        btnUpdate1.CommandName = "Update";
        btnUpdate1.Text = "Update";

        CarReg rowView = (CarReg)e.Item.DataItem;

        TextBox thisT1 = (TextBox)editedItem1.FindControl("tag_number");

        thisT1.Text = rowView.TagNumber;

        CheckBox thisC1 = (CheckBox)editedItem1.FindControl("send_mail");

        if (rowView.sendMail == "Y")
        {
          thisC1.Checked = true;
        }

        CheckBox thisC2 = (CheckBox)editedItem1.FindControl("send_email");

        if (rowView.sendEmail == "Y")
        {
          thisC2.Checked = true;
        }

      }

    }
  }
}


See other Scripts in Telerik Web Controls

Submit Your Scripts:

If you would like to have your Javascripts published in this section please fill out
the form below:
*Your Name or Username:
Home Town:
*Email:
*Description and Code:
*Enter Code shown
to the right:

[ Refresh Image ]