Reorder Gridview Asp.net JQuery : Drag Drop reorder of GridView Rows

/ / 17 Comments

Reorder Gridview: This article explains how to reorder or sort Asp.net Gridview control rows  .i.e. drag and drop row for sorting or change row position order of Gridview control with jQuery in asp.net c#.

For the drag-drop feature here we use jQuery UI sortable, using this enables the drag and drop feature on our Asp.net Gridview control.

Basically, this makes our asp.net Gridview drag and drop rows to change their row positions.

Screenshot: Reorder Gridview Asp.net JQuery : Drag Drop reorder of GridView Rows


# HTML Markup :

Here we added asp.net Gridview control and  asp.net Button control. Also need to import some js files like JQuery latest lib, jQuery Ui.js , and jQuery ui.css.

So finally our HTML markup looks like as given below

        <div>
            <asp:GridView ID="gvLanguages" CssClass="gvLanguageClass" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:TemplateField HeaderText="Sr no" ItemStyle-Width="50">
                        <ItemTemplate>
                            <%# Container.DataItemIndex + 1 %>
                            <input type="hidden" name="languageId" value='<%# Eval("id_") %>' />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField DataField="language_name" HeaderText="Language Name" ItemStyle-Width="160" />
                    <asp:BoundField DataField="developed_by" HeaderText="Developed By" ItemStyle-Width="160" />
                    <asp:BoundField DataField="sort_order" HeaderText="Sort order" ItemStyle-Width="50" />
                </Columns>
            </asp:GridView>
            <br />
            <asp:Button ID="btnUpdateSortOrder" runat="server" Text="Update Sort Order"
                OnClick="btnUpdateSortOrder_Click" />
        </div>


# DataBase:

We having a table named programming_language_info where we have 4 columns id_, language_name,  developed_by, sort_order.
CREATE TABLE [dbo].[programming_language_info](
	[id_] [bigint] IDENTITY(1,1) NOT NULL,
	[language_name] [nvarchar](150) NULL,
	[developed_by] [nvarchar](150) NULL,
	[sort_order] [bigint] NULL
) ON [PRIMARY]


# Code Behind:

First, we create a method as bindGridview,  this method will bind our Gridview control from the database and will call this method on page_load  event.
//*
protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack) {
         bindGridview();
   }
}
//*
 
//*
public void bindGridview() 
{
   string myQuery = "select id_,language_name,developed_by,sort_order from programming_language_info order by sort_order";
   SqlDataAdapter dap = new SqlDataAdapter(myQuery,cn);
   DataSet ds = new DataSet();
   dap.Fill(ds);
   gvLanguages.DataSource = ds.Tables[0];
   gvLanguages.DataBind();
}
//*
So now hit F5 and you will see our Gridview is populated with data :-) [ads_468_60]

# Jquery:  apply jQuery sortable to enable drag drop to reorder feature on Gridview.

Currently, our Gridview is populated with data, but you will find drag and drop functionality is not there.

To add drag-drop functionality on our gridview we are using jQuery UI sortable.

So we can reorder or sort Gridview rows by just a simple drag and drop row of Gridview control.

//*
$(document).ready)function(){
  $(".gvLanguageClass").sortable({
    items: 'tr:not(tr:first-child)',
    cursor: 'pointer',
    axis: 'y',
    dropOnEmpty: false,
    start: function (e, ui) {
        ui.item.addClass("selected");
    },
    stop: function (e, ui) {
        ui.item.removeClass("selected");
    },
  });
});
//*

Yeah, we are done,  Hit F5 and now you will be able to drag and drop the Gridview row, i.e reorder of Gridview row.

But there is a twist we are able to drag-drop and reorder the rows but not saving the changed rows ordering update database. So now we are going to save the changed ordering into our database.


# Code Behind: To save the position of reordered rows of Gridview into the database.

//*
protected void btnUpdateSortOrder_Click(object sender, EventArgs e)
{
    // stores id_ in array
    string [] id_language =Request.Form.GetValues("languageId");
    int sortNumber=1;
 
    // Loop over array, which contains id_ 
    foreach (string i in id_language) {
         // method which which fire update query order save into database
         updateRecord(i, sortNumber); 
         sortNumber++;
     }
     Response.Redirect(Request.RawUrl);
 }
//*
 
//*
  public void updateRecord(string languageId,int sortOrder) 
    {
        string updateQuery = "UPDATE programming_language_info SET sort_order = @sort_order WHERE id_ = @id_";
        using (SqlConnection conn = new SqlConnection(cn.ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand()) {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = updateQuery;
                cmd.Connection = conn;
                cmd.Parameters.AddWithValue("@id_", languageId);
                cmd.Parameters.AddWithValue("@sort_order",sortOrder);
                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
//*

You can also check:

  1. Sorting Gridview control on header click with pagination Asp.net.
  2. Gridview row color change based on data asp.net c#.
  3. Gridview row mouseover show detailed data in floating div  Asp.net c# jQuery.
  4. Import Excel Sheet Data to Gridview Asp.net C-sharp.
Other Resource:
  1. Drag and Drop GridView Rows using Jquery tableDnD Plugin

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

17 Comments

  1. Andy 04/30/2015 10:42:25
    Nice Article. Very well explained .. Thanks
  2. Richard David 04/30/2015 10:54:06
    Excellent post. Very good use of jquery ui sort-able for dragging and reorder the Gridview rows. Can you also provide the Solution file web pages thanks
  3. Peter 05/19/2015 11:36:08
    Thank u so much for explaining article on rearranging order of GridView Rows using drag and drop. its help me alot
  4. Satinder singh 05/22/2015 18:19:51
    Thanks for the comment, yes we can do many good things with jQuery in Asp.net :-)
  5. Satinder singh 05/22/2015 18:20:41
    Glad to help you :-)
  6. Esb 06/16/2015 22:19:24
    not judging or anything but I don't see a practical value of reordering rows. If you explain how to reorder columns on drag and drop, that'd be much more interesting
  7. Satinder singh 06/19/2015 08:46:45
    This article is about reordering gridview row, and not for gridview column. Thanks for suggestion, sure soon will write new post on how to change gridiview column.