Here's the sample for you using the Northwind database
HTML
<table>
<tr>
<td>
Sort Field:
</td>
<td>
<asp:DropDownList ID="ddlSortField" runat="server">
<asp:ListItem Text="Contact Name" Value="ContactName"></asp:ListItem>
<asp:ListItem Text="Country" Value="Country"></asp:ListItem>
<asp:ListItem Text="City" Value="City"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
</td>
<td>
Sort Direction:
</td>
<td>
<asp:DropDownList ID="ddlSortDirection" runat="server">
<asp:ListItem Text="Ascending" Value="ASC"></asp:ListItem>
<asp:ListItem Text="Descending" Value="DESC"></asp:ListItem>
</asp:DropDownList>
</td>
<td>
</td>
<td>
<asp:Button ID="btnSort" runat="server" Text="Sort" OnClick="Sort" />
</td>
</tr>
</table>
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" AllowPaging = "true" OnPageIndexChanging="OnPageIndexChanging">
<Columns>
<asp:BoundField DataField="ContactName" HeaderText="Contact Name" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvCustomers.PageIndex = e.NewPageIndex;
this.BindGrid();
}
private void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlCommand cmd = new SqlCommand("GetSortedCustomers");
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetSortedCustomers";
cmd.Parameters.AddWithValue("@SortField", ddlSortField.SelectedItem.Value);
cmd.Parameters.AddWithValue("@SortDirection", ddlSortDirection.SelectedItem.Value);
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
}
}
protected void Sort(object sender, EventArgs e)
{
this.BindGrid();
}
Namespaces
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
Stored Procedure
CREATE PROCEDURE GetSortedCustomers
@SortField VARCHAR(15),
@SortDirection VARCHAR(5)
AS
BEGIN
SET NOCOUNT ON;
SELECT [ContactName]
,[City]
,[Country]
FROM [Customers]
ORDER BY CASE WHEN @SortDirection = 'ASC' THEN
(CASE WHEN @SortField = 'ContactName' THEN ContactName
ELSE
(CASE WHEN @SortField = 'City' THEN City
ELSE
(CASE WHEN @SortField = 'Country' THEN Country END)
END)
END)
END ASC,
CASE WHEN @SortDirection = 'DESC' THEN
(CASE WHEN @SortField = 'ContactName' THEN ContactName
ELSE
(CASE WHEN @SortField = 'City' THEN City
ELSE
(CASE WHEN @SortField = 'Country' THEN Country END)
END)
END)
END DESC
END
GO