2013-09-22 27 views
3

這是彈出一個異常,說我不能在服務器端使用分頁。將數據綁定到gridview。如何使用分頁?

conn.Open(); 
string querstring = "select * from gt_transaction_log where LogTimeStamp between '2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' "; 
SqlCommand cmd = new SqlCommand(querstring, conn); 
GridView1.EmptyDataText = "no record found"; 
GridView1.DataSource = cmd.ExecuteReader(); 
GridView1.DataBind(); 

GridView1.AllowPaging = true; 
GridView1.PageSize = 5; 
+1

嘗試最後兩個命令移動DataBind方法上面。 –

+0

查看此示例:http://msdn.microsoft.com/en-us/library/aa479347.aspx –

回答

2

不能使用分頁與DataReader。所以,問題是這一行:

GridView1.DataSource = cmd.ExecuteReader();

你應該使用DatasetDatatable使用DataAdapter填充GridView控件。

例子:

//使用DataTable

string querstring = "select * from gt_transaction_log where LogTimeStamp between 
        '2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' "; 
SqlDataAdapter adapter = new SqlDataAdapter(querstring , conn); 
DataTable dt = new DataTable(); 
adapter.Fill(dt); 
GridView1.DataSource=dt; 
GridView1.DataBind(); 

//使用DataSet

string querstring = "select * from gt_transaction_log where LogTimeStamp between 
        '2013-09-19 07:06:00.077' and '2013-09-19 10:28:25.163' "; 
SqlDataAdapter adapter = new SqlDataAdapter(querstring , conn); 
DataSet ds = new DataSet(); 
adapter.Fill(ds, "Table_Name"); // you can supply a table name 
GridView1.DataSource=ds; 
GridView1.DataBind(); 
1

在設計視圖,單擊的GridView>允許分頁 或使用SqlDataSource的代替,然後讓分頁

2

,如果你想在頁面的UI分頁必須指定,那就是:

<asp:GridView ID="grid" runat="server" AllowPaging="true" PageSize="5" OnPageIndexChanging="grid_PageIndexChanging" /> 

然後在CS文件:

protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e) 
    { 
     try 
     { 
      grid.PageIndex = e.NewPageIndex; 
      BindGrid(); 
     } 
     catch (Exception ex) 
     { 
     } 
    } 

凡BindGrid()方法是在其中我們結合電網的一個。

-2

您可以嘗試使用此代碼.......

String constring = "Data Source=dsdsdsds;Initial Catalog=table;User Id=uid;Password=pass"; 
SqlConnection conqav = new SqlConnection(constring); 
String takeffty = "select top 10 * from table"; 
conqav.Open(); 
SqlCommand comqav = new SqlCommand(takeffty,conqav); 
GridView1.DataSource = comqav.ExecuteReader(); 
GridView1.DataBind(); 
conqav.Close(); 
相關問題