2016-06-01 104 views
1

我想要發生的是有一個分頁,有一個清晰的數據看看。 這裏是我的GridView的HTML代碼:添加分頁到gridview asp.net

<asp:gridview ID = "grid" runat="server" AllowPaging="true" OnPageIndexChanging="gdview_PageIndexChanging"> 

和後面的代碼:

public static string cs = "Server=PAULO;Database=ShoppingCartDB;Integrated Security=true"; 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (Session["New"] != null) 
     { 
      if (!IsPostBack) 
      { 
       SqlConnection con = new SqlConnection(cs); 
       con.Open(); 

       string sql = "SELECT * FROM CustomerDetails Where CustomerName = '" + Session["New"] +"'"; 
       SqlDataAdapter da = new SqlDataAdapter(sql, con); 
       DataTable dt = new DataTable(); 
       da.Fill(dt); 




       Label2.Text += Session["New"].ToString(); 
       linkLogout.Visible = true; 
       //linkOrderHistory.Visible = true; 
       Label2.Visible = true; 
       linkViewProfile.Visible = true; 
       grid.DataSource = dt; 
       grid.DataBind(); 
      } 
     } 

    } 
    private void CustomBindData() 
    { 
     SqlConnection con = new SqlConnection(cs); 
     con.Open(); 

     string sql = "SELECT * FROM CustomerDetails Where CustomerName = '" + Session["New"] + "'"; 
     SqlDataAdapter da = new SqlDataAdapter(sql, con); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 
    } 
    protected void gdview_PageIndexChanging(object sender, GridViewPageEventArgs e) 
    { 
     CustomBindData(); 
     grid.PageIndex = e.NewPageIndex; 
     grid.DataBind(); 
    } 

不知我的代碼不能正常工作。它有頁面,但是當我點擊頁面2時,沒有數據顯示。我認爲它有什麼關於如何從sql中獲取數據。對此有何技巧?

+0

將數據綁定部分放入一個函數中,並在兩個地方調用它,一個是在load中,另一個是在grid.DataBind()之前的pageIndexChanging。 –

+0

還不夠,你需要在自定義函數中設置源碼 –

+0

@ARUN我在想什麼? –

回答

1

我加了

private void CustomBindData() 
    { 
     SqlConnection con = new SqlConnection(cs); 
     con.Open(); 

     string sql = "SELECT * FROM CustomerDetails Where CustomerName = '" + Session["New"] + "'"; 
     SqlDataAdapter da = new SqlDataAdapter(sql, con); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 

     grid.DataSource = dt; 
     grid.DataBind(); 
    } 
    protected void gdview_PageIndexChanging(object sender, GridViewPageEventArgs e) 
    { 
     CustomBindData(); 
     grid.PageIndex = e.NewPageIndex; 
     grid.DataBind(); 
    } 
0

取而代之的是

protected void gdview_PageIndexChanging(object sender, GridViewPageEventArgs e) 
{ 
    grid.PageIndex = e.NewPageIndex; 
    grid.DataBind(); 
} 

使用following..In頁面加載儲存數據源到會話,你的使用爲GridView並執行以下操作一樣,

Session[gridviewsouce] = dt; //dataTable which you were using in page_load 

和頁換膚功能..

protected void gdview_PageIndexChanging(object sender, GridViewPageEventArgs e) 
{ 
    grid.PageIndex = e.NewPageIndex; 
    DataTabel dt = Session[gridviewsouce] as DataTable; 
    grid.DataSource = dt; 
    grid.DataBind(); 
} 
+0

不會存儲會話中的大量數據,使用viewstate [],服務器內存可能會非常快地跑出來 –

+0

@ARUN,服務器內存是否有任何限制?只是爲了澄清? –

+0

是的,取決於服務器,有些時候從谷歌專用服務器上的2GB到26GB,有分頁和其他機制來超過這個限制,但速度會降低,因爲硬盤被用來製作虛擬內存。簡單地說,有限制 –