In this article I will explain the process of GridView row reordering i.e. Drag and Drop ordering of GridView Rows using jQuery in ASP.Net.
The drag and drop ordering of GridView Rows will be performed using jQuery UI Sortable Plugin.
Database
I have made use of the following table HolidayLocations with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consists of an ASP.Net GridView control and a Button. The Location and Preference columns are populated using BoundField columns. While the Id column is populated using TemplateField and its value is also set to a HiddenField.
Note: The HiddenField is used to find the modified order of GridView Rows on server side.
<asp:GridView ID="gvLocations" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Id" ItemStyle-Width="30">
<ItemTemplate>
<%# Eval("Id") %>
<input type="hidden" name="LocationId" value='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Location" HeaderText="Location" ItemStyle-Width="150" />
<asp:BoundField DataField="Preference" HeaderText="Preference" ItemStyle-Width="100" />
</Columns>
</asp:GridView>
<br />
<asp:Button Text="Update Preference" runat="server" OnClick="UpdatePreference" />
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Linq;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Linq
Imports System.Configuration
Imports System.Data.SqlClient
Populating the GridView
The GridView is populated with the records from the HolidayLocations table inside the Page Load event.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string query = "SELECT Id, Location, Preference FROM HolidayLocations ORDER BY Preference";
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvLocations.DataSource = dt;
gvLocations.DataBind();
}
}
}
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim query As String = "SELECT Id, Location, Preference FROM HolidayLocations ORDER BY Preference"
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query)
Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
gvLocations.DataSource = dt
gvLocations.DataBind()
End Using
End Using
End Using
End Using
End Sub
Implementing Drag and Drop Functionality using jQuery
Inside the jQuery document ready event handler, the jQuery UI Sortable Plugin is applied to the GridView.
All rows except the Header row are made draggable and the Axis is set to Y axis as the GridView Rows will be dragged and dropped vertically.
In order to distinctly identify a GridView Row being dragged, a Css Class named selected is applied to the Row being dragged in the Start event handler and is removed in the Stop event handler.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=gvLocations]").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");
},
receive: function (e, ui) {
$(this).find("tbody").append(ui.item);
}
});
});
</script>
Updating the order of GridView Rows in Database
Once the GridView Row ordering is completed, the Update Preference button allows us to save the modified Order of the GridView rows to the database.
In the HTML Markup, I have discussed about a Hidden Field storing the ID field. When the Update Preference button is clicked, the Location IDs are fetched from the Request.Form collection using the Hidden Field’s name. Request.Form collection returns the Location IDs in the order of the GridView Rows.
Now a loop is executed and the preference of each Location is updated in the database.
C#
protected void UpdatePreference(object sender, EventArgs e)
{
int[] locationIds = (from p in Request.Form["LocationId"].Split(',')
select int.Parse(p)).ToArray();
int preference = 1;
foreach (int locationId in locationIds)
{
this.UpdatePreference(locationId, preference);
preference += 1;
}
Response.Redirect(Request.Url.AbsoluteUri);
}
private void UpdatePreference(int locationId, int preference)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("UPDATE HolidayLocations SET Preference = @Preference WHERE Id = @Id"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Id", locationId);
cmd.Parameters.AddWithValue("@Preference", preference);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
VB.Net
Protected Sub UpdatePreference(sender As Object, e As EventArgs)
Dim locationIds As Integer() = (From p In Request.Form("LocationId").Split(",") _
Select Integer.Parse(p)).ToArray()
Dim preference As Integer = 1
For Each locationId As Integer In locationIds
Me.UpdatePreference(locationId, preference)
preference += 1
Next
Response.Redirect(Request.Url.AbsoluteUri)
End Sub
Private Sub UpdatePreference(locationId As Integer, preference As Integer)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("UPDATE HolidayLocations SET Preference = @Preference WHERE Id = @Id")
Using sda As New SqlDataAdapter()
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@Id", locationId)
cmd.Parameters.AddWithValue("@Preference", preference)
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
End Sub
Screenshot
Demo
Downloads