将数据绑定到 网格视图.如何使用分页
本文关键字:何使用 分页 视图 网格 数据绑定 | 更新日期: 2023-09-27 18:32:24
它弹出一个异常,说我不能在服务器端使用分页。
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;
不能对DataReader
使用分页。所以问题出在这条线上:
GridView1.DataSource = cmd.ExecuteReader();
应使用Dataset
填充 GridView 或使用DataAdapter
填充Datatable
。
例:
使用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();
您必须指定是否要在页面的 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() 方法是我们在其中绑定网格的方法。
在设计视图上,单击网格视图>允许分页或改用 SQL数据源,然后允许分页
你可以尝试使用这段代码。
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();