In this article I will explain how to change the order (position) of GridView rows in ASP.Net. The order (position) of GridView Rows will be changed using Buttons in ASP.Net.
Database
For this article I have created a custom database the script of which is attached in the sample zip. The database has a table named HolidayLocations with the following schema.
The table holds the following data.
Note: You can download the database table SQL by clicking the download link below.
HTML Markup
The HTML Markup consist of an ASP.Net GridView control populated from the HolidayLocations table. The Id and the Location columns are populated using BoundField columns. While the Preference column is set as DataKeyNames in the GridView.
<asp:GridView ID="gvLocations" runat="server" AutoGenerateColumns="false" DataKeyNames="Preference"
HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" HeaderStyle-Width="50" />
<asp:BoundField DataField="Location" HeaderText="Location" HeaderStyle-Width="150" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkUp" CssClass="button" CommandArgument = "up" runat="server" Text="▲" OnClick="ChangePreference" />
<asp:LinkButton ID="lnkDown" CssClass="button" CommandArgument = "down" runat="server" Text="▼" OnClick="ChangePreference" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Populating the GridView with Holiday Locations and Preferences
The code below is quite straight forward, the GridView is being populated in the Page Load event from the HolidayLocations table and its records are ordered by the Preference. This is necessary so that when user changes its preference then the Top most preferred location must appear first.
After the GridView is populated, the Up Button for the First Row and the Down Button for the Last Row are disabled, since I does not logically makes sense to move up from first row and down from last row.
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();
}
}
}
}
LinkButton lnkUp = (gvLocations.Rows[0].FindControl("lnkUp") as LinkButton);
LinkButton lnkDown = (gvLocations.Rows[gvLocations.Rows.Count - 1].FindControl("lnkDown") as LinkButton);
lnkUp.Enabled = false;
lnkUp.CssClass = "button disabled";
lnkDown.Enabled = false;
lnkDown.CssClass = "button disabled";
}
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
Dim lnkUp As LinkButton = TryCast(gvLocations.Rows(0).FindControl("lnkUp"), LinkButton)
Dim lnkDown As LinkButton = TryCast(gvLocations.Rows(gvLocations.Rows.Count - 1).FindControl("lnkDown"), LinkButton)
lnkUp.Enabled = False
lnkUp.CssClass = "button disabled"
lnkDown.Enabled = False
lnkDown.CssClass = "button disabled"
End Sub
Handling the Up and Down Buttons and updating Preferences
When Up or Down Buttons are clicked, the ChangePreference event handler is raised. Firstly the CommandArgument is determined as it is required to identify which Button is clicked.
Then based on the RowIndex of the GridView Row whose Button is clicked, the Location Id and the Preference are determined and then with the help of fetched CommandArgument value up or down, the preference is incremented or decremented, respectively and is updated in the database table.
Next we need to update the preference of the Previous or the Next Row based on the operation performed, thus similar to above the preference is determined for the Previous or the Next Row and is updated in the database table.
C#
protected void ChangePreference(object sender, EventArgs e)
{
string commandArgument = (sender as LinkButton).CommandArgument;
int rowIndex = ((sender as LinkButton).NamingContainer as GridViewRow).RowIndex;
int locationId = Convert.ToInt32(gvLocations.Rows[rowIndex].Cells[0].Text);
int preference = Convert.ToInt32(gvLocations.DataKeys[rowIndex].Value);
preference = commandArgument == "up" ? preference - 1 : preference + 1;
this.UpdatePreference(locationId, preference);
rowIndex = commandArgument == "up" ? rowIndex - 1 : rowIndex + 1;
locationId = Convert.ToInt32(gvLocations.Rows[rowIndex].Cells[0].Text);
preference = Convert.ToInt32(gvLocations.DataKeys[rowIndex].Value);
preference = commandArgument == "up" ? preference + 1 : preference - 1;
this.UpdatePreference(locationId, preference);
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 ChangePreference(sender As Object, e As EventArgs)
Dim commandArgument As String = TryCast(sender, LinkButton).CommandArgument
Dim rowIndex As Integer = TryCast(TryCast(sender, LinkButton).NamingContainer, GridViewRow).RowIndex
Dim locationId As Integer = Convert.ToInt32(gvLocations.Rows(rowIndex).Cells(0).Text)
Dim preference As Integer = Convert.ToInt32(gvLocations.DataKeys(rowIndex).Value)
preference = If(commandArgument = "up", preference - 1, preference + 1)
Me.UpdatePreference(locationId, preference)
rowIndex = If(commandArgument = "up", rowIndex - 1, rowIndex + 1)
locationId = Convert.ToInt32(gvLocations.Rows(rowIndex).Cells(0).Text)
preference = Convert.ToInt32(gvLocations.DataKeys(rowIndex).Value)
preference = If(commandArgument = "up", preference + 1, preference - 1)
Me.UpdatePreference(locationId, preference)
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
Demo
Downloads