Simple way to Sort Gridview with corresponding Column.

Here is the sample code to sort the gridview data on the selection of column header.


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
Type ty = this.GetType();
try
{
DataView dtvv = new DataView();
DataTable dtpo = new DataTable();
public static SqlConnection cn=new SqlConnection("Connection string");;
public SqlCommand cm;
string CurrentSortColumn = SortColumn;
SortColumn = e.SortExpression;
SortDirection direction;
if (cn.State == ConnectionState.Closed) { cn.Open(); }
SqlDataReader sdr = null;
string SQLQuery="select * from databasename";
cm = new SqlCommand(SQLQuery, cn);
sdr = cm.ExecuteReader();
if (sdr != null)
{
dtpo.Load(sdr);
dtvv = new DataView(dtpo);
if (CurrentSortColumn == SortColumn)
{

if (SortAscend == true)
{
dtvv.Sort = "" + SortColumn + " DESC";
SortAscend = false;

}
else
{
dtvv.Sort = "" + SortColumn + " ASC";
SortAscend = true;
}
}
else
{
dtvv.Sort = "" + SortColumn + " ASC";
SortAscend = true;
}


GridView1.DataSource = dtvv;
GridView1.DataBind();
}
}
catch (Exception ex)
{

}
}

protected string SortColumn
{
get
{
object o = ViewState["SortColumn"];
if (o != null)
{
return (string)o;
}
else/*Default*/
{
return "";
}
}
set
{
ViewState["SortColumn"] = value;
}
}

protected bool SortAscend
{
//SortDirection
get
{
object o = ViewState["SortAscend"];
if (o != null)
{
return (bool)o;
}
else/*Default*/
{
return true;
}
}
set
{
ViewState["SortAscend"] = value;
}
}

Check this


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: