sorting and paging with gridview asp.net

前端 未结 5 1387
日久生厌
日久生厌 2020-11-27 03:15

I\'m trying to get a gridview to sort and page manually with no success.

The problem is that when a user clicks the column they want to sort, it sorts that page, but

5条回答
  •  醉话见心
    2020-11-27 03:47

     
        
            
            
            
            
            
        
    
    

    Code behind:

    protected void Page_Load(object sender, EventArgs e) {
            if (!IsPostBack) {
                string query = "SELECT * FROM book";
                DataTable DT = new DataTable();
                SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
                DA.Fill(DT);
    
                GridView1.DataSource = DT;
                GridView1.DataBind();
            }
        }
    
        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
    
            string query = "SELECT * FROM book";
            DataTable DT = new DataTable();
            SqlDataAdapter DA = new SqlDataAdapter(query, sqlCon);
            DA.Fill(DT);
    
            GridView1.DataSource = DT;
            GridView1.DataBind();
    
            if (DT != null) {
                DataView dataView = new DataView(DT);
                dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
    
                GridView1.DataSource = dataView;
                GridView1.DataBind();
            }
        }
    
        private string GridViewSortDirection {
            get { return ViewState["SortDirection"] as string ?? "DESC"; }
            set { ViewState["SortDirection"] = value; }
        }
    
        private string ConvertSortDirectionToSql(SortDirection sortDirection) {
            switch (GridViewSortDirection) {
                case "ASC":
                    GridViewSortDirection = "DESC";
                    break;
    
                case "DESC":
                    GridViewSortDirection = "ASC";
                    break;
            }
    
            return GridViewSortDirection;
        }
    }
    

提交回复
热议问题