Tuesday, 8 July 2014

Batch Editing(Edit/Insert/Update/Delete) in telerik RadGrid in ASP.NET using C#/VB.NET

Hi Friends,in this article I will explain about Batch Editing(Edit/Insert/Update/Delete) in Telerik RadGrid in ASP.NET using C#/VB.NET
I already explained in the articles about Telerik RadGrid Grouping -Drag and Drop a column header to group by that column in ASP.NET using C#/VB.NETTelerik RadGrid - Change Cell Value based on another Cell value in ASP.NET using C#/VB.NET and How to Bind the Dataset to telerik RadGrid in ASP.NET using C#/VB.NET

Write the below code in .aspx page.
ASP.NET:
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Batch Editing(Edit/Insert/Update/Delete) in telerik RadGrid in ASP.NET using C#/VB.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server" />
        <telerik:RadGrid ID="RadGridDetails" GridLines="None" runat="server" AllowSorting="true"
            OnBatchEditCommand="RadGridDetails_BatchEditCommand" AllowAutomaticUpdates="True"
            AllowAutomaticInserts="true" AllowAutomaticDeletes="true" PageSize="10" AllowPaging="True"
            OnNeedDataSource="RadGridDetails_NeedDataSource" AllowActiveRowCycle="true" AutoGenerateColumns="False"
            Width="750px" Skin="Sunset">
            <HeaderContextMenu EnableTheming="True">
                <CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation>
            </HeaderContextMenu>
            <MasterTableView DataKeyNames="User_ID" HorizontalAlign="NotSet" AutoGenerateColumns="False"
                CommandItemDisplay="TopAndBottom" EditMode="Batch">
                <BatchEditingSettings EditType="Cell" />
                <SortExpressions>
                    <telerik:GridSortExpression FieldName="User_ID" SortOrder="Descending" />
                </SortExpressions>
                <Columns>
                    <telerik:GridBoundColumn DataField="User_ID" HeaderStyle-Width="135px" HeaderText="User ID"
                        ReadOnly="true" SortExpression="User_ID" UniqueName="User_ID">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="UserName" HeaderStyle-Width="80px" HeaderText="UserName"
                        SortExpression="UserName" UniqueName="UserName">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Country" HeaderStyle-Width="80px" HeaderText="Country"
                        SortExpression="Country" UniqueName="Country">
                    </telerik:GridBoundColumn>
                    <telerik:GridBoundColumn DataField="Gender" HeaderStyle-Width="80px" HeaderText="Gender"
                        SortExpression="Gender" UniqueName="Gender">
                    </telerik:GridBoundColumn>
                    <telerik:GridButtonColumn ConfirmText="Delete this user?" ConfirmDialogType="RadWindow"
                        ConfirmTitle="Delete" HeaderText="Delete" HeaderStyle-Width="50px" ButtonType="ImageButton"
                        CommandName="Delete" Text="Delete" UniqueName="DeleteColumn">
                    </telerik:GridButtonColumn>
                </Columns>
            </MasterTableView>
        </telerik:RadGrid>
    </div>
    </form>
</body>
</html>

C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using Telerik.Web.UI;
using System.Configuration;
using System.Data;
using System.Collections;

public partial class RadGrid : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    protected void RadGridDetails_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select * from User_Details", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        RadGridDetails.DataSource = ds;
    }
    protected void BindGrid()
    {
        SqlCommand cmd = new SqlCommand("Select * from User_Details", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        RadGridDetails.DataSource = ds.Tables[0];
        RadGridDetails.DataBind();
    }
    protected void RadGridDetails_BatchEditCommand(object sender, GridBatchEditingEventArgs e)
    {

        foreach (GridBatchEditingCommand command in e.Commands)
        {
            Hashtable oldValues = command.OldValues;
            Hashtable newValues = command.NewValues;
            if (command.Type == GridBatchEditingCommandType.Update)
            {
                string UserName = newValues["UserName"] == null ? null : newValues["UserName"].ToString();
                string Country = newValues["Country"] == null ? null : newValues["Country"].ToString();
                string Gender = newValues["Gender"] == null ? null : newValues["Gender"].ToString();
                string User_ID = newValues["User_ID"] == null ? null : newValues["User_ID"].ToString();

                string str = "UPDATE user_details SET UserName='" + UserName + "',Country='" + Country + "',Gender='" + Gender + "'  WHERE user_id= " + User_ID;

                SqlCommand cmd = new SqlCommand(str, con);
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();
            }
            else if (command.Type == GridBatchEditingCommandType.Insert)
            {
                string UserName = newValues["UserName"] == null ? null : newValues["UserName"].ToString();
                string Country = newValues["Country"] == null ? null : newValues["Country"].ToString();
                string Gender = newValues["Gender"] == null ? null : newValues["Gender"].ToString();
                string User_ID = newValues["User_ID"] == null ? null : newValues["User_ID"].ToString();

                string str = "INSERT INTO user_details(Username,Country,Gender) VALUES('" + UserName + "','" + Country + "','" + Gender + "' )";

                SqlCommand cmd = new SqlCommand(str, con);
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();
            }

            else if (command.Type == GridBatchEditingCommandType.Delete)
            {
                string User_ID = newValues["User_ID"] == null ? null : newValues["User_ID"].ToString();
                string str = "DELETE FROM user_details WHERE user_id= " + User_ID;

                SqlCommand cmd = new SqlCommand(str, con);
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();

            }
        }
    }

}

The output of the above code as shown in the below figure.When you click on cell then it will be converted to edit mode after changing the change it will mark as red in the left top corner as shown in the below figure.
After click on Save Changes button then all the cell values having red mark in the left top corner will be updated.

"If you like my blog or articles, you can appreciate by leaving your comments or Liking my Facebook page Aspdotnet-kishore, following on Google+ Aspdotnet-Kishore, Twitter on AspdotnetKishore, Linked in Aspdotnet-Kishore, stumbling my posts on stumble upon and subscribing on RSSfeed Aspdotnet-Kishore for free updates directly to your Email inbox . Watch my blog for more articles."

4 comments:

  1. I like turtles

    ReplyDelete
  2. Thank you very much, I had several days of being "stuck" with this topic. Greetings.

    ReplyDelete

© 2012-2014 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.