Search code examples
c#gridviewsqldatareadersqldataadapterpage-index-changed

Using SqlDataAdapter to page a SqlDataReader source


This question seems to be common and I went through this answer already.

Unfortunately, my page still isn't being paged. Here's what my code looks like in C#:

 SqlCommand command = new SqlCommand("(SELECT ......", Connection);
 SqlDataAdapter myAdapter = new SqlDataAdapter(command);
 DataTable dt = new DataTable();
 myAdapter.Fill(dt);

 command.Connection = connection;
 command.Connection.Open();

 GridView1.DataSource = dt;
 GridView1.DataBind();
 GridView1.AllowPaging = true;
 GridView1.PageSize = 15;

 command.Connection.Close();
 command.Connection.Dispose();

Unfortunately, when I do this, my paging doesn't show up. Am I doing something wrong?

Thanks


Solution

  • Set all of the Paging-related properties before the Databind() method is called. When you use Custom Paging you will have to handle the GridView1_PageIndexChanging event. You need to change the current PageIndex, and re-bind your GridView like this:

    void bindGridview()
    {
        SqlCommand command = new SqlCommand("(SELECT ......", Connection);
        SqlDataAdapter myAdapter = new SqlDataAdapter(command);
        DataTable dt = new DataTable();
        myAdapter.Fill(dt);
    
        command.Connection = connection;
        command.Connection.Open();
        GridView1.AllowPaging = true;
        GridView1.PageSize = 15;
        GridView1.DataSource = dt;
        GridView1.DataBind();
    
    
        command.Connection.Close();
        command.Connection.Dispose();
    }
    
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        bindGridview();
    }
    

    If you are also binding the GridView on Page_Load, do it like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
            bindGridview();
    }