<asp:GridView
ID="GridView1" runat="server" AutoGenerateColumns="false" AllowSorting="True" onsorting="GridView1_Sorting" EnableViewState="true">
<Columns>
<asp:BoundField DataField="bookid" HeaderText="BOOK ID"SortExpression="bookid" />
<asp:BoundField DataField="bookname" HeaderText="BOOK NAME" />
<asp:BoundField DataField="writer" HeaderText="WRITER" />
<asp:BoundField DataField="totalbook" HeaderText="TOTALBOOK" SortExpression="totalbook" />
<asp:BoundField DataField="availablebook" HeaderText="AVAILABLE BOOK" />
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
string query = "SELECT * FROM book";
DataTable DT = new DataTable();
SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
DA.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
if (DT != null) {
DataView dataView = new DataView(DT);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridView1.DataSource = dataView;
GridView1.DataBind();
}
}
private string GridViewSortDirection {
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string ConvertSortDirectionToSql(SortDirection sortDirection) {
switch (GridViewSortDirection) {
case "ASC":
GridViewSortDirection = "DESC";
break;
case "DESC":
GridViewSortDirection = "ASC";
break;
}
return GridViewSortDirection;
}
}