5

我的网格视图

<div style="margin-left: 280px">
   <asp:GridView ID="exportGrdVw" runat="server" BackColor="White"  
        AllowPaging="True" PageSize="3" 
        OnPageIndexChanging="exportGrdVw_PageIndexChanging" 
        onpageindexchanged="exportGrdVw_PageIndexChanged">
   </asp:GridView>
</div>

我的代码

SqlConnection con = new SqlConnection("server=acer-Pc\\Sql;database=MYDB;trusted_connection=yes");  
//DataSet ds = new DataSet();
DataTable table = new DataTable();    
protected void Page_Load(object sender, EventArgs e)
{        
    if (!IsPostBack)
    {
        SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
        da.Fill(table);
        BindEmployee();
    }
 }
 public void BindEmployee()
 {
    exportGrdVw.DataSource = table;
    exportGrdVw.DataBind();
 }
 protected void exportGrdVw_PageIndexChanging(object sender, GridViewPageEventArgs e)
 {
    exportGrdVw.PageIndex = e.NewPageIndex;
    BindEmployee();
 }

问题是 gridview 正在显示,但是当我单击第 2 页时。第 2 页数据未显示(空白)。请帮我解决这个问题。查看代码是否正确

4

4 回答 4

13

像下面这样使用

SqlConnection con = new SqlConnection("server=acer-Pc\\Sql;database=MYDB;trusted_connection=yes");
//DataSet ds = new DataSet();
DataTable table = new DataTable();    
protected void Page_Load(object sender, EventArgs e)
{        
   if (!IsPostBack)
   {              
       BindEmployee();
   }
}
public void BindEmployee()
{
    SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
    da.Fill(table);
    exportGrdVw.DataSource = table;
    exportGrdVw.DataBind();
}
protected void exportGrdVw_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    exportGrdVw.PageIndex = e.NewPageIndex;
    BindEmployee();
}
于 2013-03-28T15:29:11.533 回答
0

您的数据表在每次页面加载时都会被初始化,因此您需要在每次将其绑定到网格之前获取数据表。在将页面绑定到网格之前设置页面索引

所以你的代码应该是这样的

public void BindEmployee(int newPageIndex = -1)
{
    SqlDataAdapter da = new SqlDataAdapter("select customername,contactno,address from employee ", con);
    da.Fill(table);
    exportGrdVw.PageIndex = newPageIndex;
    exportGrdVw.DataSource = table;
    exportGrdVw.DataBind();
}
于 2013-03-28T15:22:35.197 回答
0

无需在exportGrdVw_PageIndexChanging上调用数据库。只需将 DataTable 表声明为静态

于 2016-09-15T18:59:48.667 回答
-1

你可以试试这个:

GridView1.PageIndex = e.NewPageIndex;
SqlCommand cmd = new SqlCommand("Select * from Emp_Data ORDER BY [ID] DESC", con);

SqlDataAdapter DA1 = new SqlDataAdapter(cmd);
DA1.Fill(DT1);

GridView1.DataSource = DT1;
GridView1.DataBind();
于 2017-04-17T01:26:58.070 回答