The GridView 'grid' fired event PageIndexChanging which wasn't handled

Amit Kumar picture Amit Kumar · Jun 7, 2013 · Viewed 8.1k times · Source
public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string connectionString =
            WebConfigurationManager.ConnectionStrings["base"].ConnectionString;
            string selectSQL = "SELECT author,book FROM ListItem";
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adapter.Fill(ds, "ListItem");
            grid.DataSource = ds;
            grid.DataBind();  
        }
        protected void grid_PageIndexChanged(object sender, EventArgs e)
        {
            grid.PageIndex=e.NewPageIndex;//have a error    grid.DataBind();                                      

        }
    }

Answer

Magnus picture Magnus · Jun 7, 2013

You have handled the wrong event, change it to PageIndexChanging. (and you need to hook it up in the aspx code)

protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   grid.PageIndex = e.NewPageIndex;
   grid.DataBind();
}

And you need to surround the binding of the grid in the page load with a if(!Page.IsPostback){//do binding }