This is a migrated thread and some comments may be shown as answers.
Add Row on Client Side only
3 Answers 286 Views
This is a migrated thread and some comments may be shown as answers.
mfmz
Top achievements
Rank 1
mfmz asked on 19 May 2009, 07:29 AM
Hi,
I need to add a row on client side only without AJAX or Postback call. I try it in 2 ways but I am not able to render Template column on client side without AJAX or Postback.
1) I define a JSON array of items which will bcome data source by calling masterTableView.set_dataSource(). This array will store in hidden field and pass to server side on final postback.
2) I add rows(TR) and cells(TD) and set their values manually

In both approaches I am not able to rendered Template Item of Templete Column. on calling set_dataSource(), OnRowCreating client side event does not fire. Is it default?

Client Side:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default2.aspx.cs" Inherits="TestGrid._Default2" %> 
 
<%@ 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 runat="server"
    <title>Untitled Page</title> 
     
    <script type="text/javascript" src="script/jquery/1.3.2/jquery.js"></script> 
    <script type="text/javascript" src="json.js"></script> 
    <telerik:RadScriptBlock ID="SB" runat="server">         
     
    <script type="text/javascript"
    var dataItems = new Array(); 
    var dataRows = 0
    var empId = -999; 
    var employee = 
    { 
        EmployeeID : null, 
        FirstName : null, 
        LastName : null, 
        Title : null, 
        TitleOfCourtesy : null, 
        BirthDate : null, 
        Notes : null, 
         
        create : function() 
        { 
            var obj = new Object(); 
 
            obj.EmployeeID = 0
            obj.FirstName = ""
            obj.LastName = ""
            obj.Title = ""
            obj.TitleOfCourtesy = ""
            obj.BirthDate = ""
            obj.Notes = ""
 
            return obj; 
        } 
    }; 
     
    $(document).ready(pageLoad); 
     
    function pageLoad() 
    { 
        var grd = $find("<%= RadGrid1.ClientID %>");  
        //loadGrid(grd);         //Approach 1 
        loadGrid2(grd);          //Approach 2       
    }             
         
    function addEmployee() 
    {                    
        var newEmployee = employee.create(); 
        newEmployee.FirstName = "Taimur"
        newEmployee.LastName = "Khan"
        newEmployee.EmployeeID = empId--; 
        newEmployee.Title = "Mr"
        newEmployee.Notes = "XYZ"
        newEmployee.BirthDate = "12-12-1970"
         
        var grd = $find("<%= RadGrid1.ClientID %>"); 
         
        //Approach 1 
        //addNewItem(grd,newEmployee);                    
         
        //Approach 2 
        addNewItem2(grd,newEmployee);      
        dataItems[dataRows] = newEmployee;               
        document.getElementById("hdEmployees").value = $.toJSON(dataItems);   
    }    
         
    function loadGrid(grd) 
    { 
        if(grd == null) 
            return; 
             
        var masterTable = grd.get_masterTableView(); 
        if(masterTable == null) 
            return; 
             
        var ds = document.getElementById("hdEmployees").value; 
        if(ds && ds != "") 
        { 
            masterTable.set_dataSource($.parseJSON(ds)); 
            masterTable.dataBind(); 
        } 
    } 
     
    function addNewItem(grd,dataItem) 
    {  
        if(grd == null || dataItem == null) 
            return; 
             
        var masterTable = grd.get_masterTableView(); 
        if(masterTable == null) 
           return; 
 
        var ds = masterTable.get_dataSource(); 
        if(!ds) 
            ds = new Array(); 
             
        ds[ds.length] = dataItem; 
         
        masterTable.set_dataSource(ds); 
        masterTable.dataBind(); 
                 
        document.getElementById("hdEmployees").value = $.toJSON(ds);      
    } 
     
    function loadGrid2(grd) 
    { 
        if(grd == null) 
            return; 
        var ds = document.getElementById("hdEmployees").value; 
        if(ds && ds != "") 
        { 
            dataItems = $.parseJSON(ds);       
        } 
    } 
     
    function addNewItem2(grd,dataItem) 
    { 
        var masterTable = grd.get_masterTableView(); 
        if(masterTable == null) 
            return; 
       
        if(dataRows == 0) 
        { 
            dataRows = masterTable.get_dataItems().length; 
            if(dataRows == 0) 
            { 
                //delete row of "No record" 
                masterTable._element.deleteRow(masterTable._element.rows.length-1); 
            } 
        } 
                    
        var tBodyNode = null
        for(var i=0;i<masterTable._element.childNodes.length;i++) 
        { 
            var node = masterTable._element.childNodes[i]; 
            if(node.nodeName == "TBODY") 
            { 
                tBodyNode = node
                break; 
            }     
        }     
        if(tBodyNode != null) 
        { 
            tBodyNode.insertRow(-1);                
               
            var newRowIndex = masterTable._element.rows.length - 1;             
            var row = masterTable._element.rows[newRowIndex];                                 
            row.id = masterTable._element.id + "__" + newRowIndex;                                                 
            row.className = (dataRows == 0 || dataRows % 2 == 0) ? "rgRow" : "rgAltRow"; 
                                 
            debugger; 
             
            var columns = masterTable.get_columns(); 
            for(var i=0;i<columns.length;i++) 
            {       
                var uniqueName = columns[i]._data.UniqueName; 
                                       
                masterTable._element.rows[newRowIndex].insertCell(i);             
                var td = masterTable._element.rows[newRowIndex].cells[i];                                                       
                 
                if(uniqueName == "EmployeeID") 
                { 
                    td.innerHTML = dataItem.EmployeeID; 
                    td.style.display = "none"
                } 
                     
                if(uniqueName == "mode") 
                { 
                   td.innerHTML = "Add"
                   td.style.display = "none"
                } 
                     
                if(uniqueName == "FirstName") 
                    td.innerHTML = dataItem.FirstName; 
                     
                if(uniqueName == "LastName") 
                    td.innerHTML = dataItem.LastName;                 
                     
                if(uniqueName == "Title") 
                    td.innerHTML = dataItem.Title; 
                     
                if(uniqueName == "TitleOfCourtesy") 
                    td.innerHTML = ""
                                    
                if(uniqueName == "BirthDate") 
                    td.innerHTML = dataItem.BirthDate; 
                     
                if(uniqueName == "Notes") 
                    td.innerHTML = dataItem.Notes;                                                 
            } 
                         
            dataRows++;             
         }                      
    } 
     
    function OnCommand(sender,args) 
    { 
       debugger; 
       $get("<%= Panel1.ClientID %>").innerHTML = String.format("<b>RadGrid1_Command</b><br />CommandName : {0}, CommandArgument : {1} <br /><br  />", args.get_commandName(), args.get_commandArgument()); 
       
       //args.set_cancel(true); 
       if(args.get_commandName() == "InitInsert") 
       { 
          alert(""); 
       } 
       
       var currentPageIndex = sender.get_masterTableView().get_currentPageIndex(); 
       var pageSize = sender.get_masterTableView().get_pageSize(); 
       var sortExpressions = sender.get_masterTableView().get_sortExpressions(); 
       var filterExpressions = sender.get_masterTableView().get_filterExpressions(); 
       
       if(sortExpressions.length > 0 && filterExpressions.length > 0 && currentPageIndex > 0) 
       { 
           sender.get_masterTableView().set_currentPageIndex(0); 
       } 
       
       var sortExpressionssortExpressionsAsSQL = sortExpressions.toString(); 
       var filterExpressionsfilterExpressionsAsSQL = filterExpressions.toString(); 
       
        
    } 
    function OnRowDataBound(sender,args) 
    { 
       var row = sender.get_masterTableView().get_dataItems()[0]; 
       var cell = sender.get_masterTableView().getCellByColumnUniqueName(row, "CurrencyId"); 
       // conditional formatting 
       args.get_item().get_cell("TitleOfCourtesy").style.fontWeight = (args.get_dataItem()["TitleOfCourtesy"] == "Dr.")? "bold" : "normal"; 
       var sb = new Sys.StringBuilder(); 
       
       sb.appendLine("<b>RadGrid1_RowDataBound</b><br />"); 
       
       for(var item in args.get_dataItem()) 
       { 
           sb.appendLine(String.format("{0} : {1}<br />", item, args.get_dataItem()[item])); 
       } 
       
       sb.appendLine("<br />"); 
       sb.appendLine("<br />"); 
       $get("<%= Panel1.ClientID %>").innerHTML += sb.toString(); 
    } 
    function OnDataBinding(sender,args) 
    { 
         
    } 
    function OnRowCreating(sender,args) 
    { 
         
    } 
    </script> 
     
    </telerik:RadScriptBlock> 
</head> 
<body > 
    <form id="form1" runat="server"
    <div> 
        <asp:ScriptManager ID="ScriptManager1" runat="server" ></asp:ScriptManager> 
        <telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1NeedDataSource" > 
        <MasterTableView AutoGenerateColumns="false"  EditMode="InPlace" AllowAutomaticInserts="true" DataKeyNames="EmployeeID"  CommandItemDisplay="Top"
         
        <Columns> 
        <telerik:GridBoundColumn DataField="EmployeeID" Display="false" DataType="System.Int32">         
        </telerik:GridBoundColumn> 
         
        <telerik:GridBoundColumn DataField="mode" Display="false">         
        </telerik:GridBoundColumn> 
         
        <telerik:GridBoundColumn DataField="FirstName" HeaderText="First Name">               
        </telerik:GridBoundColumn> 
        
        <telerik:GridBoundColumn DataField="LastName" HeaderText="Last Name">               
        </telerik:GridBoundColumn> 
         
        <telerik:GridBoundColumn DataField="Title" HeaderText="Title">             
        </telerik:GridBoundColumn> 
         
        <telerik:GridBoundColumn DataField="TitleOfCourtesy" HeaderText="Title Of Courtesy" >             
        </telerik:GridBoundColumn> 
         
        <telerik:GridBoundColumn DataField="BirthDate"  HeaderText="BirthDate" >             
        </telerik:GridBoundColumn> 
         
         <telerik:GridBoundColumn DataField="Notes" HeaderText="Notes">             
        </telerik:GridBoundColumn>        
       <telerik:GridTemplateColumn HeaderText="Curr" UniqueName="CurrencyId"
            <HeaderStyle Width="40px" HorizontalAlign="Center" VerticalAlign="Top" /> 
            <ItemTemplate> 
            
                <asp:DropDownList 
                    ID="drpCurrency" 
                    runat="server" 
                    Enabled="true" 
                    CssClass="select"  
                    Width="50px"  
                      
                    onchange="DoCalculations(event);" > 
                    <asp:ListItem Text="Item 1" Value="1">Item 1</asp:ListItem> 
                    <asp:ListItem Text="Item 2" Value="2">Item 2</asp:ListItem> 
                    <asp:ListItem Text="Item 3" Value="3">Item 3</asp:ListItem> 
                </asp:DropDownList> 
             </ItemTemplate> 
             <ItemStyle Width="5%" HorizontalAlign="Center" VerticalAlign="Top"  /> 
        </telerik:GridTemplateColumn>   
        </Columns> 
        <CommandItemTemplate> 
        <input type="button" value="+" id="add" onclick="addEmployee();" /> 
        </CommandItemTemplate> 
                 
        </MasterTableView> 
        <ClientSettings> 
        <ClientEvents OnCommand="OnCommand" OnDataBinding="OnDataBinding" OnRowCreating="OnRowCreating"  /> 
        </ClientSettings> 
        </telerik:RadGrid> 
         
        <asp:Button ID="button1" runat="server" OnClick="button1_Click"  /> 
        <asp:HiddenField ID="hdEmployees" runat="server" /> 
    </div> 
     
   
     
      <br /> 
       <br /> 
       Events: 
       <asp:Panel ID="Panel1" Style="height: 200px; overflow: auto; padding: 15px;" CssClass="module" 
           runat="server"
       </asp:Panel> 
    </form> 
</body> 
</html> 
Server SIde:
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 
using System.Web.Services; 
using System.Web.Script.Services; 
using System.Reflection; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Schema; 
 
using CS.DataAccessLayer.EntityClasses; 
using CS.DataAccessLayer.CollectionClasses; 
using CS.CommonLib.ErrorHandling; 
using CS.BusinessClasses.Helpers; 
using CS.BusinessClasses.SystemAndApp; 
using CS.DataAccessLayer.HelperClasses; 
using CS.DataAccessLayer; 
using CS.BusinessClasses; 
using Telerik.Web.UI; 
using System.Globalization; 
using System.Drawing; 
using CS.DataAccessLayer.CSTypes; 
using CS.DataAccessLayer.FactoryClasses; 
using CS.DataAccessLayer.DaoClasses; 
using CS.DataAccessLayer.RelationClasses; 
//Check line 1651 
using SD.LLBLGen.Pro.ORMSupportClasses; 
 
 
namespace TestGrid 
    
    public partial class _Default2 : System.Web.UI.Page 
    { 
         
        protected void Page_Load(object sender, EventArgs e) 
        { 
             
        }              
 
        protected void RadGrid1NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e) 
        { 
            RadGrid1.MasterTableView.DataSource = Employees; 
        }         
 
        protected void button1_Click(object sender, EventArgs e) 
        {             
            _employees = (List<Employee>)JsonConvert.DeserializeObject(hdEmployees.Value, typeof(List<Employee>)); 
            RadGrid1.Rebind(); 
        }             
 
        private List<Employee> _employees = new List<Employee>(); 
        public List<Employee> Employees 
        { 
            get { return _employees; }             
        } 
         
    } 
public class Employee 
    { 
        string firstName = ""
        public string FirstName 
        { 
            get { return firstName; } 
            set { firstName = value; } 
        } 
        int employeeId = 0; 
        public int EmployeeID 
        { 
            get { return employeeId; } 
            set { employeeId = value; } 
        } 
        string lastName = ""
        public string LastName 
        { 
            get { return lastName; } 
            set { lastName = value; } 
        } 
        string title = ""
        public string Title 
        { 
            get { return title; } 
            set { title = value; } 
        } 
        string toc = ""
        public string TitleOfCourtesy 
        { 
            get { return toc; } 
            set { toc = value; } 
        } 
         
        public string BirthDate = ""
        public string Notes = ""
    } 
   } 
 



3 Answers, 1 is accepted

Sort by
0
Nikolay Rusev
Telerik team
answered on 22 May 2009, 07:11 AM
Hello,

I am afraid that I do not completely understand what you are trying to achieve.
You are trying to binding RadGrid on server and then rebind it on client with additional items in datasource?
If this is the case you can serialize the datasource from server side to client side and save it in local variable. When you add employee you will add that new Employee client object to that array/which is already populated from server side/ and bind/on client/ RadGrid with the new set of data.

Regards,
Nikolay
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
manish
Top achievements
Rank 1
answered on 10 Jun 2009, 11:08 AM

Hi
I am facing issue with client side grid row manipulation, plz help me to overcome of this-

I have two different grids, both have first column as GridClientSelectColumn(checkbox),
First grid is full of data and second grid is blank.

Now I want that when I check checkbox of first grid this row will need to be added into second grid
and should be remove respectively while i unselect checked checkbox of first grid.


also, Is there any demo available for this.
can you send me sample code.

With thanks and regards
Manish sain


0
Nikolay Rusev
Telerik team
answered on 12 Jun 2009, 01:42 PM
Hello Manish,

Generally you can use same approach as the following demo:
Grid / Master/Details Client-side Data Binding

Other option is on client RowSelected event to extract all the data for the current Item and store it in predefined javascript array and use that array as data source for the second grid.
For the purpose you can use RadGrid client-side api:
http://www.telerik.com/help/aspnet-ajax/grid_gridtableviewclassmembers.html
http://www.telerik.com/help/aspnet-ajax/grdextractkeyvaluesclientside.html

Best wishes,
Nikolay
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
Tags
Grid
Asked by
mfmz
Top achievements
Rank 1
Answers by
Nikolay Rusev
Telerik team
manish
Top achievements
Rank 1
Share this question
or