Wael Sayed

Wael Sayed

Monday, September 22, 2008

How to Sort GridView by code

hello , In this article we will discuss in sorting gridview .

Sorting gridview very easy if you connected with dataset typed or SqlDataSource etc.. But it's not similar if you retrieve your data by DAL(Data Access layer) or method returns a collection of data.

In this example we use DataView to sort data

let's start

1- Drag a gridView on a simple page (GridPersons)


2- create a method returns DataView object to populated gridview



public DataView GetDate()
{
using (SqlConnection con = new SqlConnection("Server=.;DataBase=AdventureWorks;integrated security=SSPI;"))
{
try
{
SqlCommand com = con.CreateCommand();
com.CommandText = "Select FirstName , LastName,EmailAddress from person.Contact";
con.Open();
SqlDataAdapter dap = new SqlDataAdapter();
dap.SelectCommand = com;
DataSet ds = new DataSet();
dap.Fill(ds);
DataTable personTable = ds.Tables[0];
DataView dv = new
DataView(personTable);

if (ViewState["sortExpr"] != null && ViewState["OrderBy"] != null)
{
if (ViewState["OrderBy"].ToString() == "Desc")
{
ViewState["OrderBy"] = "Asc";
}
else
{
ViewState["OrderBy"] = "Desc";
}

dv.Sort = (string)ViewState["sortExpr"] + " " + (string)ViewState["OrderBy"];
}
return dv;
}
finally
{
con.Dispose();
}
}
}

3- Add GridView Sorting Event and write this code



protected void GridPersons_Sorting(object sender, GridViewSortEventArgs e)
{
ViewState["sortExpr"] = e.SortExpression;
Session["EditMode"] = null;
if (ViewState["OrderBy"] == null)
{
ViewState["OrderBy"] = "Desc";
}
GridPersons.DataSource = GetDate();
GridPersons.DataBind();
}

4- In Page Load add this code


protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridPersons.DataSource = GetDate();
GridPersons.DataBind();
}
}


No comments: