Hi Amol111,
I have created a sample which full fill your requirement
HTML
<div>
<asp:GridView ID="GridView1" runat="server" AllowSorting="true" AllowPaging="true"
PageSize="10" OnSorting="GridView1_Sorting" OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>
</div>
C#
public string sortDirection
{
get
{
return ViewState["sortDirection"] == null ? "ASC" : ViewState["sortDirection"].ToString();
}
set
{
ViewState["sortDirection"] = value;
}
}
public string sortExpression
{
get
{
return ViewState["SortExpression"] == null ? "CustomerID" : ViewState["SortExpression"].ToString();
}
set
{
ViewState["SortExpression"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}
private DataTable BindData()
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(strConnString))
{
string strQuery = "SELECT TOP 20 CustomerID,ContactName,City FROM Customers";
SqlCommand cmd = new SqlCommand(strQuery);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
if (sortDirection == e.SortDirection.ToString())
{
sortDirection = "Descending";
sortExpression = e.SortExpression.ToString();
SortGridView(sortExpression, sortDirection.ToString());
}
else
{
sortDirection = "Ascending";
sortExpression = e.SortExpression.ToString();
SortGridView(sortExpression, sortDirection.ToString());
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
DataView dv = new DataView(BindData());
if (sortDirection == "Ascending")
{
dv.Sort = sortExpression + " " + "ASC";
}
else
{
dv.Sort = sortExpression + " " + "DESC";
}
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
SortGridView(sortExpression, sortDirection);
}
ScreenShot