Showing posts with label sorting n paging for gv. Show all posts
Showing posts with label sorting n paging for gv. Show all posts

22 August 2011

Grid view sorting in asp.net using code

SqlConnection con = new SqlConnection("Data Source=...;Initial Catalog=...;Persist Security Info=True;User ID=sa;Password=...");
SqlDataAdapter da;
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetData();
}
void GetData()
{
DataTable dt = new DataTable();
da = new SqlDataAdapter("select * from sample",con);
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dt = new DataTable();
da = new SqlDataAdapter("select * from sample", con);
da.Fill(dt);
dt.DefaultView.Sort = e.SortExpression + direction();

GridView1.DataSource = dt;
GridView1.DataBind();
}
string direction()
{
if (ViewState["stat"] != null && ViewState["stat"].ToString().Trim() == "desc")
{
ViewState["stat"] = " asc";
return " asc";
}
else
{
ViewState["stat"] = " desc";
return " desc";
}
}