Realization of Gridview automatic sorting function
- 2020-06-03 08:10:54
- OfStack
Two points to note:
1. To set the AllowSorting attribute of gridview to true, set the OnSorting event
2. Set the SortExpression attribute on the sorted columns in the OnSorting event
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["Admin"] != "admin")
{
// If the session expires, you should log in again
this.Response.Write(" <script language=javascript>alert(' You do not have access to this page, please contact the administrator! ');window.location.href='../UserLogin.aspx';</script> ");
}
ViewState["sortExpression"] = "Isdistribution";
ViewState["sort"] = " ASC";
}
// The binding information
BindNodeInfo();
}
public void BindNodeInfo()
{
NodeLogic log = new NodeLogic();
DataSet myset = log.GetNodeInfo(); // Get data source
DataView myview = myset.Tables[0].DefaultView;
myview.Sort = ViewState["sortExpression"].ToString() +" "+ ViewState["sort"].ToString();
this.NodeGridView.DataSource = myview;
NodeGridView.DataKeyNames = new string[] { "node_id" }; // Set the primary key field
NodeGridView.DataBind(); // The binding GridView controls
}
protected void NodeGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.NodeGridView.PageIndex = e.NewPageIndex;
BindNodeInfo();
}
protected void NodeGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
// Automatically to the first 1 Column number
if (e.Row.RowIndex > -1)
{
e.Row.Cells[0].Text = Convert.ToString(e.Row.RowIndex + 1);
}
}
protected void NodeGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
NodeLogic log = new NodeLogic();
int id = int.Parse(this.NodeGridView.DataKeys[e.RowIndex].Values[0].ToString());
if (log.DeleteNodeInfo(id))
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert(' Delete successful! ');", true);
}
else
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert(' Delete failed! ');", true);
// Re-update the data display
BindNodeInfo();
}
protected void NodemGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
}
protected void AddNode_Click(object sender, EventArgs e)
{
Response.Redirect("AddNode.aspx");
}
protected void NodeGridView_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["sortExpression"] != null)
{
if (ViewState["sort"].ToString() == "Asc")
{
ViewState["sort"] = "Desc";
}
else
{
ViewState["sort"] = "Asc";
}
}
BindNodeInfo();
}