gridview reorder row drag and drop — gridview reorder jquery , jQuery — ASP.Net Example
ASP.Net Example-gridview reorder row drag and drop

Sunday, October 2, 2011

gridview reorder row drag and drop

Drag and Drop GridView Row with jQuery.
Save Display Order in DataBase with WebMethod.
nodrag and nodrop for row that you are not want to drag and drop

gridview reorder row drag and drop




GridViewReOrderDragandDrop.aspx
<%@ Page Language="C#" CodeFile="GridViewReOrderDragandDrop.aspx.cs"
 AutoEventWireup="true" Inherits="GridViewReOrderDragandDrop" %>

<!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">
    <script src="jquery-1.6.1.js" type="text/javascript"></script>
    <script src="jquery.tablednd_0_5.js" type="text/javascript"></script>
    <style>
        .noselect
        {
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -o-user-select: none;
            user-select: none;
            cursor: move;
        }
        .tDnD_whileDrag
        {
            background-color: Lime;
        }
    </style>
    <title>ASPdotNET-Example.blogspot.com</title>

<script type="text/javascript">
var strorder;
$(document).ready(function() {
$('#GridViewReorder').tableDnD(
{
    onDrop: function(table, row) {
    reorder();
    $.ajax({
             type: "POST",
             url: "GridViewReOrderDragandDrop.aspx/GridViewReorders",
             data: '{"Reorder":"'+strorder+'"}',
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             cache: false,
             success: function (msg) {
             alert("Successfully Save ReOrder");
             }

           })
     }
}
);
});
function  reorder()
{ 
    strorder="";
    var totalid=$('#GridViewReorder tr td input').length;
    for(var i=0;i<totalid;i++)
    {
     strorder=strorder+$('#GridViewReorder tr td input')[i].getAttribute("value")+"|";
    }
}
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <center>
    <h1>GridView Reorder Drag And Drop</h1>
 <div>
 <asp:GridView ID="GridViewReorder" runat="server" HeaderStyle-CssClass="nodrag nodrop"
AutoGenerateColumns="False">
 <Columns>
    <asp:TemplateField ItemStyle-CssClass="noselect" HeaderText="ID">
      <ItemTemplate>
        <asp:Label ID="lblID" runat="server" Text='<%# Bind("id") %>'></asp:Label>
       <asp:HiddenField ID="hdnid" runat="server" Visible="true" Value='<%# Bind("id") %>' />
      </ItemTemplate>
     </asp:TemplateField>
        <asp:TemplateField ItemStyle-CssClass="noselect" HeaderText="Name">
       <ItemTemplate>
         <asp:Label ID="lblName" runat="server" Text='<%# Bind("name") %>'></asp:Label>
         </ItemTemplate>
        </asp:TemplateField>
     <asp:TemplateField HeaderText="Display Order" ItemStyle-CssClass="noselect">
        <ItemTemplate>
          <asp:Label ID="lblOrder" runat="server" Text='<%# Bind("displayorder") %>'>
</asp:Label>
          </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
</div>
    <h1> ASPdotNet-Example.blogspot.com</h1>
    </center>
    </form>
</body>
</html>
 


GridViewReOrderDragandDrop.aspx.cs

using System;
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.Data.SqlClient;
using System.Web.Services;
public partial class GridViewReOrderDragandDrop : System.Web.UI.Page 
{
    SqlConnection strCon;
    string sql;
    SqlDataAdapter objAd;
    DataSet objDs;
    protected void Page_Load(object sender, EventArgs e)
    {
        GridViewReorder.DataSource = Con();
        GridViewReorder.DataBind();
    }
    protected DataSet Con()
    {
strCon = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
        objAd = new SqlDataAdapter("ListGrid", strCon);
        objDs = new DataSet();
        objAd.Fill(objDs);
        return objDs;
    }
    [WebMethod]

    public static void GridViewReorders(string Reorder)
    {
        string[] ListID = Reorder.Split('|');
        for (int i = 0; i < ListID.Length; i++)
        {
            if (ListID[i] != "" && ListID[i] !=null)
            {
                updateGridViewReorder(Convert.ToInt16(ListID[i]), i+1);
            }
        }

    }


    public static void updateGridViewReorder(int id, int DisplayOrder)
    {SqlConnection con ;
con= new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
        SqlCommand cmd = new SqlCommand("UpdateOrder");
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = con;
        cmd.Parameters.AddWithValue("@id", id);
        cmd.Parameters.AddWithValue("@DisplayOrder",DisplayOrder);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    
    }
}

 Database Script

 SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (
SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[GridViewReorder]') AND type in (N'U')
)
BEGIN
CREATE TABLE [dbo].[GridViewReorder](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [name] [nvarchar](50) NULL,
 [displayorder] [int] NULL
) ON [PRIMARY]
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (
SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[ListGrid]') AND type in (N'P', N'PC')
)
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ==============================
-- Author:  <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[ListGrid] 

AS
BEGIN
select * from GridViewReorder order by displayorder
END

' 
END
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (
SELECT * FROM sys.objects 
WHERE object_id = OBJECT_ID(N'[dbo].[UpdateOrder]') AND type in (N'P', N'PC')
)
BEGIN
EXEC dbo.sp_executesql @statement = N'-- ============================
-- Author:  <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[UpdateOrder] 
@id int,
@DisplayOrder int 
AS
BEGIN
 update GridViewReorder set displayorder=@DisplayOrder where id=@id
END
' 
END

 

19 comments:

  1. please provide the code for the page GridViewReOrderDragandDrop.aspx/GridViewReorders where jason is used

    thanks

    ReplyDelete
    Replies
    1. welcome,

      This is page GridViewReOrderDragandDrop.aspx.cs and in that page GridViewReorders webmethod already written .
      refer this post you will get idea behind that
      http://aspdotnet-example.blogspot.in/2011/07/calling-aspnet-method-from-jquery.html

      Delete
  2. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
    html5 audio player

    ReplyDelete
  3. Hi , I tried the same code as over here but somehow the web method is not getting called using jquery. I was able to get the grid with sortable rows and it is sorting the rows but once i drop the row the sort order is not getting updated in the database because the web method is not getting called. May be i am making mistake in ajax call or something

    ReplyDelete
  4. This is working better than most other examples out there, but for some reason I'm always getting: {"Reorder":"null|null|null|null|null|null|null|null|null|"} (using Fiddler)

    It's not picking up any of the values. Any thoughts why?

    ReplyDelete
  5. I have not more idea about Fiddler.

    ReplyDelete
  6. Hi there,

    This is a great solution, but I too find that the web method is not getting called. I'm using jQuery 1.7.1 and tablednd 0.7 so I don't know if that's causing it. Can you shed any light on which might be causing it. I've put breakpoints in the code and it looks like it's not even firing the onDrop function.

    Many thanks

    ReplyDelete
  7. mail me your pages.I will solve you problem. what is your email address ? comment here

    ReplyDelete
  8. GridViewReorders(string Reorder) method is not firing

    ReplyDelete
  9. Give your email address I will solve it.

    ReplyDelete
  10. Hi, for me also, ondrop method is not getting called. Please help. It is being called If i replace gridview with html table but with gridview, ondrop function is not getting called. Could you please check your code above or update the code above to make it work with gridview...thanks in advance.

    ReplyDelete
    Replies
    1. Most Welcome.
      Give your email address I will solve it.
      Thanks you.

      Delete
  11. Hi,

    I'm also having an issue with the onDrop event not being fired.

    When I try with an HTML table instead of a gridview it works fine. As soon as I use the gridview the onDrop event does not fire.
    Any ideas?

    ReplyDelete
  12. If onDrop event doesn't fire. Please add this to your code,

    $(document).ready(function () {
    var i = 0;
    $("#GridViewName").find('tr').each(function()
    {
    $(this).attr('id', i++);
    });
    }

    This will add an id to each row which is important to fire the onDrop event.

    ReplyDelete
  13. Thanks for sharing this article. Its help me.

    ReplyDelete
  14. Help please
    Just where do you put this

    $(document).ready(function () {
    var i = 0;
    $("#GridViewName").find('tr').each(function()
    {
    $(this).attr('id', i++);
    });
    }

    ReplyDelete
    Replies
    1. where do you put this $(document).ready(function () {
      var i = 0;
      $("#GridViewName").find('tr').each(function()
      {
      $(this).attr('id', i++);
      });
      }

      Delete
  15. HI INDrop Method is not called for me also..
    can you please solve the error?

    ReplyDelete

ASPdotNET-Example