Tutorial :Code to create Sorting for a GridView in ASP.net in Code Behind?



Question:

This is my code code for the Page_Load Event

            OdbcConnection myConnection;              DataSet dataSet = new DataSet();              OdbcDataAdapter adapter;                //making my connection              myConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings  ["ODBC_ConnectionString"].ConnectionString);                adapter = new OdbcDataAdapter("SELECT * from Company", myConnection);                adapter.Fill(dataSet, "MyData");                GridView1.DataSource = dataSet;              Session["DataSource"] = dataSet;              GridView1.DataBind();  

This is my code for the PageIndexChanging event and it all works fine.

           DataSet ds = new DataSet();                if (Session["DataSource"] != null)                  ds = ((DataSet)Session["DataSource"]);                GridView1.DataSource = ds;              GridView1.PageIndex = e.NewPageIndex;              this.GridView1.DataBind();  

Now what code do i need to create the Sorting event?

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)      {          ?????????????????????????      }  

Etienne


Solution:1

I usually do this:

 public string SortField {              get {                  return (string) ViewState["_sortField"];              }              set {                  ViewState["_sortField"] = value;              }          }          public string SortDir {              get {                  return (string) ViewState["_sortDir"];              }              set {                  ViewState["_sortDir"] = value;              }          }  

Put your code to do databinding into another Method because you have to call it during Sort, Paging, and when your page first loads. Call it DoDataBind() for example. Then you have in DoDataBind()

DataTable dt = yourDataSet.Tables[0];  dt.DefaultView.Sort = SortField + " " + SortDir;    GridView1.DataSource = dt.DefaultView;  GridView1.DataBind();  

Then your event looks like this:

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {                if (e.SortExpression == SortField && SortDir != "desc") {                  SortDir = "desc";              }              else {                  SortDir = "asc";              }                SortField = e.SortExpression;                DoDataBind();          }  

Then in your aspx page you'll need to specify what the SortExpression is. For example something like this:

<asp:BoundField DataField="FIRSTNAME"   HeaderText="First Name" SortExpression="FIRSTNAME" />  


Solution:2

You can filter and sort your dataset using:

ds.Tables[0].Select(filterExp, sortExp, etc...);  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »