Wednesday, February 27, 2008

How To Sort GridView Columns

public partial class GridView : System.Web.UI.Page
{
SqlConnection Con = new SqlConnection(@"Server=yourservername;Database=pubs;uid=userid;password=pwd;");
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();


protected void Page_Load(object sender, EventArgs e)
{
gv.DataSource = GetData();
gv.DataBind();
}

public DataTable GetData()
{
da = new SqlDataAdapter("Select * from authors", Con);
da.Fill(dt);
return dt;
}

protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
string stExp = e.SortExpression;
string stDir = string.Empty;
if (StDir == SortDirection.Ascending)
{
StDir = SortDirection.Descending;
stDir= "DESC";
}
else
{
StDir = SortDirection.Ascending;
stDir="ASC";
}
DataTable dt = GetData();
DataView dv = new DataView(dt);
dv.Sort = e.SortExpression + " " + stDir;
gv.DataSource = dv;
gv.DataBind();
}
public SortDirection StDir
{
get
{
if (ViewState["sortDirection"] == null)
{
ViewState["sortDirection"] = SortDirection.Ascending;
}return (SortDirection)ViewState["sortDirection"];
}
set
{
ViewState["sortDirection"] = value;
}
}
}

No comments: