This is a migrated thread and some comments may be shown as answers.

How to insert item programmatically without saving all other items first

5 Answers 349 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Jeroen
Top achievements
Rank 1
Jeroen asked on 11 Jul 2011, 07:04 PM
I'm trying to programmatically insert items in radgrid while having all items in edit mode.
The item needs to be inserted and saved immediately so more items can be inserted. Please see below sample project.

I noticed that raising both the InitInsertCommandName and PerformInsertCommandName commands will cause the grid's datasource to fire selecting event again. All changes the user made in the grid will be lost because of this.
Does this mean i have to update the entire grid first, before i insert the item? Is there a better way to achieve described functionality?

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RadGridAdd._Default" %>
 
<%@ Register Assembly="Telerik.Web.UI, Version=2011.1.413.35, Culture=neutral, PublicKeyToken=121fae78165ba3d4"
    Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<%@ Register Assembly="Microsoft.Practices.Web.UI.WebControls, Version=2.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="Microsoft.Practices.Web.UI.WebControls" TagPrefix="pp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
    </telerik:RadScriptManager>
    <div>
        <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="False" CellSpacing="0"
            DataSourceID="ObjectContainerDataSource1" GridLines="None" AllowAutomaticInserts="true"
            AllowMultiRowEdit="true" OnItemCommand="RadGrid1_ItemCommand"
            onprerender="RadGrid1_PreRender">
            <MasterTableView DataKeyNames="Id" EditMode="InPlace" CommandItemDisplay="Top" >
                <Columns>
                     
                    <telerik:GridBoundColumn DataField="Id" DataType="System.Int32" FilterControlAltText="Filter Id column"
                        HeaderText="Id" SortExpression="Id" UniqueName="Id">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Abc" FilterControlAltText="Filter Abc column"
                        HeaderText="Abc" SortExpression="Abc" UniqueName="Abc">
                    </telerik:GridBoundColumn>
                    <telerik:GridButtonColumn ButtonType="ImageButton" CommandName="InitInsertAndPerformSave"
                        Text="ADD" UniqueName="AddColumn" ShowInEditForm="true">
                        <ItemStyle HorizontalAlign="Center" CssClass="MyImageButton" />
                    </telerik:GridButtonColumn>
                </Columns>
            </MasterTableView>
        </telerik:RadGrid>
    </div>
    <pp:ObjectContainerDataSource ID="ObjectContainerDataSource1" runat="server" DataObjectTypeName="RadGridAdd.A"
        OnSelecting="ObjectContainerDataSource1_Selecting"
        OnInserted="ObjectContainerDataSource1_Inserted"
        onupdated="ObjectContainerDataSource1_Updated" />
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using Microsoft.Practices.Web.UI.WebControls;
 
namespace RadGridAdd
{
    [Serializable]
    public class A
    {
        public int Id { get; set; }
        public string Abc { get; set; }
    }
 
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < RadGrid1.PageSize; i++)
            {
                RadGrid1.EditIndexes.Add(i);
            }
        }
 
        private List<A> Data
        {
            get { return ViewState["data"] as List<A>; }
            set { ViewState["data"] = value; }
        }
 
        protected void ObjectContainerDataSource1_Selecting(object sender, ObjectContainerDataSourceSelectingEventArgs e)
        {
            if (Data == null)
            {
                List<A> la = new List<A>();
                la.Add(new A() { Id = 1, Abc = "123" });
                la.Add(new A() { Id = 2, Abc = "456" });
 
                Data = la;
            }
 
            ObjectContainerDataSource1.DataSource = Data;
        }
 
        protected void ObjectContainerDataSource1_Inserted(object sender, ObjectContainerDataSourceStatusEventArgs e)
        {
            A new_a = (A)e.Instance;
 
            Data.Add(new_a);
            //RadGrid1.Rebind();
        }
 
        protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "InitInsertAndPerformSave")
            {
                GridCommandItem GCI = (GridCommandItem)RadGrid1.MasterTableView.GetItems(GridItemType.CommandItem)[0];
                RadGrid1.MasterTableView.NoMasterRecordsText = string.Empty;
                GCI.FireCommandEvent(RadGrid.InitInsertCommandName, String.Empty);
                var gi = RadGrid1.MasterTableView.GetInsertItem();
                gi.FireCommandEvent(RadGrid.PerformInsertCommandName, string.Empty);
            }
        }
 
        protected void RadGrid1_PreRender(object sender, EventArgs e)
        {
            GridCommandItem GCI = (GridCommandItem)RadGrid1.MasterTableView.GetItems(GridItemType.CommandItem)[0];
            GCI.Visible = false;
        }
 
        protected void ObjectContainerDataSource1_Updated(object sender, ObjectContainerDataSourceStatusEventArgs e)
        {
 
        }
    }
}

5 Answers, 1 is accepted

Sort by
0
Genti
Telerik team
answered on 15 Jul 2011, 05:24 PM
Hi Jeroen,

Can you please clarify why you are using just one button for both functionalities(updating and inserting records)?
What will happen if a user clicks on an item that is already created?

Regards,
Genti
the Telerik team

Register for the Q2 2011 What's New Webinar Week. Mark your calendar for the week starting July 18th and book your seat for a walk through of all the exciting stuff we will ship with the new release!

0
Jeroen
Top achievements
Rank 1
answered on 18 Jul 2011, 11:01 PM
I'm not using a single button for add/update. The sample is a little confusing but the button on the right (that is shown in every row) should add a new item to the grid. However instead of having to click the green checkmark as in this http://demos.telerik.com/aspnet-ajax/grid/examples/dataediting/alleditablecolumns/defaultcs.aspx example, i want the item to be inserted immediately.
Updating will only be done by a different button which i do not have in the example. My question is if it is possible to insert an item (invoke initinsert and performinsert on the newly created GridCommandItem), without having to save the entire grid first?
0
Genti
Telerik team
answered on 19 Jul 2011, 03:42 PM
Hi Jeroen,

If you want to perform a batch insert than you would have to employ some client side programming in order to achieve that. In this way you can save the grid inserted items without contacting the server.

Otherwise, you can make a simple trick to the grid insert command to keep the grid in insert mode all the time.
protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
{
    //Here manually perform the insertion to your data source
 
    //Then set the grid in edit mode again
    RadGrid1.MasterTableView.IsItemInserted = true;
 
    //Rebind it so that it shows the updated source
    RadGrid1.Rebind();
 
    //We cancel the automatic operation as now we are done with inserting
    e.Canceled = true;
}
However, in contrast to the previous option, this solution requires you to postback and rebind on each insertion.


Regards,
Genti
the Telerik team

Register for the Q2 2011 What's New Webinar Week. Mark your calendar for the week starting July 18th and book your seat for a walk through of all the exciting stuff we will ship with the new release!

0
Jeroen
Top achievements
Rank 1
answered on 22 Jul 2011, 07:05 PM
Thanks for your reply Genti. This definitely helped although i have 1 more follow up question. It seems like both approaches, client side insert (i looked at this example http://demos.telerik.com/aspnet-ajax/grid/examples/client/insertupdatedelete/defaultcs.aspx), and the code you suggested, both go back to the data source.
According to my requirements i can only write to database when the user is done editing the grid and i'll do some batch update. I would like to avoid having some buffer data source as suggested here http://www.telerik.com/community/forums/aspnet-ajax/grid/how-can-i-insert-multiple-row-in-radgrid.aspx
I think i'm good as long as the grid doesn't rebind. This link http://www.telerik.com/help/aspnet/grid/apiforcontrolling_net2.html mentions i can call PerformInsert (GridEditableItem, [boolean suppressRebind]) and suppress the rebind but i couldn't figure out how to obtain the new GridEditableItem.
Do you know if it is possible to implement my scenario without having to have a buffer data source?
0
Genti
Telerik team
answered on 28 Jul 2011, 02:20 PM
Hi Jeroen,

The idea that you are presenting using PerformInsert won't work in this case as the PerformInsert method is going to Rebind the grid itself.


Regards,
Genti
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

Tags
Grid
Asked by
Jeroen
Top achievements
Rank 1
Answers by
Genti
Telerik team
Jeroen
Top achievements
Rank 1
Share this question
or