Fields not changing in Formview when moving Pagina

2019-08-20 08:14发布

问题:

I have a formview that on page load makes a call to a sql server and retrieves 5 records which I want the formview to paginate though.

I have sucessfully connected to the db, filled a dataset, and returned data when the web page renders. The problem is that when I move to a new page, the data does not change in the databound field.

Here is my code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        conn = new SqlConnection(connstr);
        ds = new DataSet();
        da = new SqlDataAdapter("call to stored proc", conn);

        try

        {
            conn.Open();
            da.Fill(ds, "m");
            FormView1.DataSource = ds;
            FormView1.DataKeyNames = new string[] { "PropKey" };
            FormView1.DataBind();
        }
        catch (Exception ex)
        {
            Result = ex.Message;
        }
        finally
        {
            conn.Close();
        }
    }

Next when the paginate buttons are clicked I have this:

protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
    FormView1.PageIndex = e.NewPageIndex;
}

Please help, Thanks

回答1:

You will need to bind the data to the FormView just after setting the new page index like below.

protected void FormView1_PageIndexChanging1(object sender, FormViewPageEventArgs e)
{
    FormView1.PageIndex = e.NewPageIndex;
    BindFormViewData();
}

This is required because the FormView only displays the data for the active record and does not store any other records from the datasource, so upon change of the page index, the datasource is required to be bound again. See: Paging in a FormView Web Server Control

From the above link:

If the FormView control is bound to a data source control, or to any data structure that implements the ICollection interface (including datasets), the control gets all the records from the data source, displays the record for the current page, and discards the rest. When the user moves to another page, the FormView control repeats the process, displaying a different record.

Hope this helps.