Diogo Peixoto
Diogo Peixoto

Reputation: 33

PageIndexChanging problems

The GridView 'Sqldata' fired event PageIndexChanging which wasn't handled. How to handle it?

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

and

<-asp:GridView  ID="Sqldata" runat="server" autoGenerateColumns ="False" ShowFooter ="True" showHeaderWhenEmpty="True" EmptyDataText="Dado Não Encontrado" AllowPaging="True"              
              Width="1100px" Height="350px" CssClass="auto-style5" Font-Names="Arial" HorizontalAlign="Center" PageSize="20">

Full Code

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.ComponentModel;



namespace WebApplication5
{
    public partial class Lis_Mov_Admin : System.Web.UI.Page
    {
        //Connection String,  criada pelo web form Configuração. (Caminho do servidor. EX: Data Source = Nome/SQLEXPRESS; Initial Catalog = table; user Id = sa; password = 1234) 
        string connection = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Session["Nome"].ToString() == "SuperAdministrador") //Para poder usar o super-administrador criado em código...
                {
                    Label2.Text = Session["Nome"].ToString();
                }
                else if (Session["Nome"] != null && Session["Funcao"].ToString() == "1")// Evitar que o utilizador navegue via URL e verificando se o nome está vazio ou funcao diferente da do site
                {
                    Label2.Text = Session["Nome"].ToString();
                }
                else
                {
                    Response.Redirect("Login.aspx");
                    Label2.Text = Session["Nome"].ToString();
                }
            }
            catch (Exception)
            {
                Response.Redirect("Login.aspx");//Se o utilizador arrancar com esta página é rederecionado para a página login (ou então dava erro)
            }
            if (!IsPostBack)//Verifica se a página foi carregada a primeria vez ou não
            {
                populateGridView();//Variavél Criada do tipo void
            }
        }
         public void populateGridView()
        {
            DataTable dtbl = new DataTable();
            using (SqlConnection sqlCon = new SqlConnection(connection))
            {
                sqlCon.Open();
                SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT  * FROM Movimentos", sqlCon);//Mostra os dados inseridos na tabela referida
                sqlDa.Fill(dtbl);
            }
            if (dtbl.Rows.Count > 0)
            {
                Sqldata.DataSource = dtbl;
                Sqldata.DataBind();
            }
            else
            {
                dtbl.Rows.Add(dtbl.NewRow());
                Sqldata.DataSource = dtbl;
                Sqldata.DataBind();
                Sqldata.Rows[0].Cells.Clear();
                Sqldata.Rows[0].Cells.Add(new TableCell());
                Sqldata.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
                Sqldata.Rows[0].Cells[0].Text = "Não foi encontrado dados...";
                Sqldata.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Lis_Mov_Admin.aspx"); //Mostrar tudo
        }


        protected void Button3_Click(object sender, EventArgs e)
        {
            //Pesquisa os dados da tabela usando textbox

            string filter = "";
            string command = "SELECT * FROM Movimentos WHERE";


            if (textDataMovimento.Text != "")
            {
                filter = filter + "[Data Movimento] LIKE '%" + textDataMovimento.Text + "%' AND";
            }
            if (textDataValor.Text != "")
            {
                filter = filter + " [Data Valor] LIKE '%" + textDataValor.Text + "%' AND";
            }
            if (textDescricao.Text != "")
            {
                filter = filter + " [Descricao] LIKE '%" + textDescricao.Text + "%' AND";
            }
            if (textValor.Text != "")
            {
                filter = filter + " [Valor] LIKE '%" + textValor.Text + "%' AND";
            }
            if (textTipodeMovimento.Text != "")
            {
                filter = filter + " [Tipo de Movimento] LIKE '%" + textTipodeMovimento.Text + "%'AND";
            }
            if (filter.Length > 0)
            {
                Sqldata.DataSource = SqlDataSource1;
                string FinalFilter = filter.Remove(filter.Length - 3);
                SqlDataSource1.SelectCommand = command + FinalFilter;
                Sqldata.DataBind();
            }
            else
            {
                Sqldata.DataBind();
            }
        }
        public override void VerifyRenderingInServerForm(System.Web.UI.Control control)
        {
            //confirms that an HtmlForm control is rendered for the
            //specified ASP.NET server control at run time.
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.AppendHeader("content-disposition", "attachment; filename=register.xls");
            Response.ContentType = "applicantion/excel";
            StringWriter ad = new StringWriter();
            HtmlTextWriter sd = new HtmlTextWriter(ad);
            Sqldata.RenderControl(sd);
            Response.Write(ad.ToString());
            Response.End();
        }
        protected void myButton_1_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Imp_Mov_Admin.aspx");
        }
        protected void myButton_2_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Imp_Doc_Admin.aspx");
        }
        protected void myButton_3_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Lis_Mov_Admin.aspx");
        }
        protected void myButton_4_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Lis_Doc_Admin.aspx");
        }
        protected void myButton_6_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Dados_Sinc_Admin.aspx");
        }
        protected void myButton_5_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Dados_Nao_Admin.aspx");
        }
        protected void myButton_7_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Criar_Contas_Admin.aspx");
        }
        protected void mybutton_8_Click(object sender, EventArgs e)
        {
            Session["Nome"] = null;
            Response.Redirect("~/Login.aspx");
        }
        protected void Sqldata_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            Sqldata.PageIndex = e.NewPageIndex;
            Sqldata.DataSource= sqlCon ;
            Sqldata.DataBind();
            DataBind();

        }
    }    
}

Upvotes: 2

Views: 143

Answers (2)

Gowtham Belliraj
Gowtham Belliraj

Reputation: 56

I hope you need to do a small change in Sqldata_PageIndexChanging

Remove the following two lines

Sqldata.DataSource= sqlCon ; Sqldata.DataBind();

and add populateGridView method below to Sqldata.PageIndex = e.NewPageIndex;

Upvotes: 1

sr28
sr28

Reputation: 5106

Following the comments I'll put the steps here to summarize:

In the html you need to ensure 'onpageindexchanging' is referencing your method like this onpageindexchanging="Sqldata_PageIndexChanging".

In your 'Sqldata_PageIndexChanging' method you need to ensure your data is being rebound to the gridview. Looking at your code you initially populate the data grid using 'populateGridView' method. Assuming the data bound to the gridview in this method is the data source you need you should split the part of this that gets the data and puts it into your datatable out, so it can be referenced elsewhere. Alternatively, if the data doesn't change you can store it into a global variable and reference it where you need it. Ultimately, in your 'Sqldata_PageIndexChanging' method you need to set the DataSource like this:

protected void Sqldata_PageIndexChanging(object sender, GridViewPageEventArgs e)
 {
    Sqldata.PageIndex = e.NewPageIndex;
    Sqldata.DataSource= //your data source whether from global variable or new method;
    Sqldata.DataBind();
 }

Upvotes: 1

Related Questions