Tuesday 9 February 2016

ASP.NET - GridView - edit cell after double click


In this example - I will save changes to the database after double clicking cell in gridview.


1. Create the following table
CREATE TABLE [dbo].[Customers](
    [CustomerID] [int] IDENTITY(1,1) NOT NULL,
    [CustomerFirstName] [varchar](50) NOT NULL,
    [CustomerLastName] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
    [CustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Customers] ON

GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (1, N'Bob3', N'Dylan1')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (2, N'Oleh 1', N'Skrypka')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (3, N'Frank', N'Sinatra')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (4, N'John ', N'Lennon')
GO
INSERT [dbo].[Customers] ([CustomerID], [CustomerFirstName], [CustomerLastName]) VALUES (5, N'Mick ', N'Jagger')
GO
SET IDENTITY_INSERT [dbo].[Customers] OFF
GO

2. First Stored Procedure

 Create PROCEDURE [dbo].[GetAllCustomers]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Select * From Customers
END
3.  Second Stored Procedure
CREATE PROCEDURE [dbo].[GetCustomerByCustomerID]
    @CustomerID int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Select * From Customers Where CustomerID = @CustomerID
END
4. Third Stored Procedure
CREATE PROCEDURE [dbo].[UpdateCustomers]
    @CustomerID int,
    @CustomerFirstName varchar(50),
    @CustomerLastName varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    Update Customers Set CustomerFirstName = @CustomerFirstName, CustomerLastName = @CustomerLastName
    Where CustomerID  = @CustomerID
END
5. here is my customers class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace WebApplication12
{
    public class Customers
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class CustomerDA
    {
        private SqlConnection connection;
        private string connectionString = Convert.ToString(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnectionString"]);
        private SqlCommand command;
        private SqlDataAdapter adapter;
        private DataSet dataset;

        public DataSet GetAllCustomers()
        {
            try
            {
                adapter = default(SqlDataAdapter);
                connection = new SqlConnection(connectionString);
                command = new SqlCommand("GetAllCustomers", connection);
                dataset = new DataSet();
                adapter = new SqlDataAdapter(command);
                adapter.Fill(dataset);
                return dataset;
            }
            finally
            {
                if (connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                    connection.Dispose();
                }
                if (command != null)
                {
                    command.Dispose();
                }
            }
        }

        public DataSet GetCustomerByCustomerID(String ID)
        {
            try
            {
                adapter = default(SqlDataAdapter);
                connection = new SqlConnection(connectionString);
                command = new SqlCommand("GetCustomerByCustomerID", connection);
                command.Parameters.Add("@CustomerID", SqlDbType.Int);
                command.Parameters["@CustomerID"].Value = Convert.ToInt32(ID);
                dataset = new DataSet();
                command.CommandType = CommandType.StoredProcedure;
                adapter = new SqlDataAdapter(command);
                adapter.Fill(dataset);
                return dataset;
            }
            finally
            {
                if (connection.State != ConnectionState.Closed)
                {
                    connection.Close();
                    connection.Dispose();
                }
                if (command != null)
                {
                    command.Dispose();
                }
            }
        }

        public Customers UpdateCustomer(Customers c)
        {
            command = new SqlCommand("UpdateCustomers");
            try
            {
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@CustomerID", SqlDbType.Int);
                command.Parameters.Add("@CustomerFirstName", SqlDbType.VarChar, 50);
                command.Parameters.Add("@CustomerLastName", SqlDbType.VarChar, 50);
                command.Parameters["@CustomerID"].Value = c.ID;
                command.Parameters["@CustomerFirstName"].Value = c.FirstName;
                command.Parameters["@CustomerLastName"].Value = c.LastName;
                using (connection = new SqlConnection(connectionString))
                {
                    command.Connection = connection;
                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                }
            }
            catch(Exception ex){
                //handle exception
            }
            return c;
           
        }
    }
}
6. HTML file
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication12.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".CustomerFirstName").dblclick(function (e) {
                e.stopPropagation();
                var currentEle = $(this);
                var value = $(this).html();
                var row = $(e.target).closest('tr');
                var CustomerID = row.find($("[id*=key]")).val();
                UpdateVal(currentEle, value, CustomerID, "CustomerFirstName");
            });
            $(".CustomerLastName").dblclick(function (e) {
                e.stopPropagation();
                var currentEle = $(this);
                var value = $(this).html();
                var row = $(e.target).closest('tr');
                var CustomerID = row.find($("[id*=key]")).val();
                UpdateVal(currentEle, value, CustomerID, "CustomerLastName");
            });
        });
        function UpdateVal(CurrentEle, value, CustomerID, ColumnToUpdate) {
            if ($(".cellValue") !== undefined) {
                if ($(".cellValue").val() !== undefined) {
                    $(".cellValue").parent().html($("#OriginalValue").val().trim());
                    $(".cellValue").remove();
                }
                if (value.match("<") == null) {
                    $(CurrentEle).html('<div class="cellValue" id"cellWrapper"> ' +
                        ' <input class="cellValue" type="text" id="txtValue" value="' + value + '" />' +
                        ' <input class="cellValue" type="hidden" value="' + CustomerID + '" id="keySelected" />' +
                        ' <input class="cellValue" type="hidden" value="' + ColumnToUpdate + '" id="ColumnToUpdate" />' +
                        ' <input class="cellValue" type="hidden" value="' + value + '" id="OriginalValue" />' +
                        ' <input class="cellValue" type="button" value="Save" id="btnSave" onClick="return SaveChanges()" />' +
                        ' <input class="cellValue" type="button" value="Cancel" id="btnCancel" onClick="return CancelChanges()" /> ' +
                        ' </div> ');
                }
                $(".cellValue").focus();
                $(".cellValue").keyup(function (event) {
                    if (event.keyCode == 13) {
                        $(CurrentEle).html($(".cellValue").val().trim());
                    }
                });
            }
        }

        function CancelChanges(e) {
            if ($(".cellValue") !== undefined) {
                if ($(".cellValue").val() !== undefined) {
                    $(".cellValue").parent().html($("#OriginalValue").val().trim());
                    $(".cellValue").remove();
                }
            }
            window.location.reload();
        }
        function SaveChanges(e) {
            var customer = {};
            customer.ColumnToUpdate = $("[id*=ColumnToUpdate]").val();
            customer.FieldValue = $("[id*=txtValue]").val();
            customer.ID = $("[id*=keySelected]").val();
            $.ajax({
                type: "POST",
                url: "WebForm1.aspx/SaveCustomer",
                data: '{customer: ' + JSON.stringify(customer) + '}',
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("saved!");
                    location.href = location.href;
                    window.location.reload();
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HiddenField ID="key" runat="server" Value='<%# Eval("CustomerID") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="First Name">
                    <ItemTemplate>
                        <asp:Label ID="Label1" CssClass="CustomerFirstName" runat="server" Text='<%# Bind("CustomerFirstName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Name">
                    <ItemTemplate>
                        <asp:Label ID="Label2" CssClass="CustomerLastName" runat="server" Text='<%# Bind("CustomerLastName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>
7. code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Services;
using System.Web.Script.Services;

namespace WebApplication12
{
    public class CustomerToUpdate
    {
        public int ID { get; set; }
        public string FieldValue { get; set; }
        public string ColumnToUpdate { get; set; }
    }

    public partial class WebForm1 : System.Web.UI.Page
    {


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = LoadData();
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
        protected DataTable LoadData()
        {
            CustomerDA usr = new CustomerDA();
            return usr.GetAllCustomers().Tables[0];
        }

        [WebMethod]
        [ScriptMethod]
        public static void SaveCustomer(CustomerToUpdate customer)
        {
            Customers upd = new Customers();
            CustomerDA da = new CustomerDA();
            DataSet ds = da.GetCustomerByCustomerID(customer.ID.ToString());
            upd.FirstName = (string)ds.Tables[0].Rows[0]["CustomerFirstName"];
            upd.LastName = (string)ds.Tables[0].Rows[0]["CustomerLastName"];
            upd.ID = (int)ds.Tables[0].Rows[0]["CustomerID"];
            switch (customer.ColumnToUpdate)
            {
                case "CustomerFirstName":
                    upd.FirstName = customer.FieldValue;
                    break;
                case "CustomerLastName":
                    upd.LastName = customer.FieldValue;
                    break;
                default:
                    break;
            }
            upd = da.UpdateCustomer(upd);
        }
    }
}


2 comments:

  1. what changes needed to use it in content page of master page?

    ReplyDelete
  2. How To Do - Ms Sql C Excel Access: Asp.Net - Gridview - Edit Cell After Double Click >>>>> Download Now

    >>>>> Download Full

    How To Do - Ms Sql C Excel Access: Asp.Net - Gridview - Edit Cell After Double Click >>>>> Download LINK

    >>>>> Download Now

    How To Do - Ms Sql C Excel Access: Asp.Net - Gridview - Edit Cell After Double Click >>>>> Download Full

    >>>>> Download LINK wr

    ReplyDelete