PageIndexChanging问题

时间:2019-06-27 08:50:26

标签: c# html gridview

未处理的GridView'Sqldata'激发事件PageIndexChanging。 如何处理?

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

<-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">

完整代码

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();

        }
    }    
}

2 个答案:

答案 0 :(得分:1)

在评论之后,我将在此处进行总结:

在html中,您需要确保“ onpageindexchanging”正在引用您的方法,例如onpageindexchanging =“ Sqldata_PageIndexChanging”。

在您的'Sqldata_PageIndexChanging'方法中,您需要确保数据正在反弹到gridview。查看您的代码,最初使用“ populateGridView”方法填充数据网格。假设此方法中绑定到gridview的数据是您需要的数据源,则应将获取数据的部分拆分为一部分,并将其放入数据表中,以便可以在其他地方引用。另外,如果数据不变,则可以将其存储到全局变量中,并在需要时引用它。最终,在您的'Sqldata_PageIndexChanging'方法中,您需要像这样设置DataSource:

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();
 }

答案 1 :(得分:1)

我希望您需要在 Sqldata_PageIndexChanging

中进行一些更改

删除以下两行

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

并将下面的populateGridView方法添加到Sqldata.PageIndex = e.NewPageIndex;