Sunday, August 19, 2007

Gird View Sorting and Paging


Sorting of Gridview

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds=bindata();
GridView1.DataSource = ds;
GridView1.DataBind();
}
}
private DataSet bindata()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["deoConnectionString1"].ToString());
con.Open();
string cmd = "select id,name, employee.desgid,designation, employee.deptid,deptname,address from employee left outer join" +
" dept on (employee.deptid=dept.deptid)" +
" left outer join " +
" designation on (employee.desgid=designation.desgid)";
SqlDataAdapter da = new SqlDataAdapter(cmd,con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
DataView dv = sortedView(false);
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
ViewState["col"] = e.SortExpression;
DataView dv= sortedView(true);
GridView1.DataSource = dv;
GridView1.DataBind();
}
private DataView sortedView(Boolean isSort)
{
DataTable dt = bindata().Tables[0];
DataView dv = new DataView(dt);
if (ViewState["order"] == null ViewState["order"].ToString() == "asc")
{
if (isSort)
{
dv.Sort = ViewState["col"].ToString() + " Desc";
ViewState["order"] = "desc";
}
else
{
if(ViewState["order"] != null)
dv.Sort = ViewState["col"].ToString() + " asc";
}
}
else
{
if (isSort)
{
dv.Sort = ViewState["col"].ToString() + " asc";
ViewState["order"] = "asc";
}
else
{
if(ViewState["order"] != null)
dv.Sort = ViewState["col"].ToString() + " desc";
}
}
return dv;
}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
DataView dv = sortedView(false);
GridView1.DataSource = dv;
GridView1.DataBind();
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
DataView dv = sortedView(false);
GridView1.DataSource = dv;
GridView1.DataBind();
}

this code will sort the gridview by ascending and desceding order.