IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Pagination d'une datagrid [Débutant]


Sujet :

C#

  1. #1
    Expert confirmé Avatar de Toufik83
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2012
    Messages
    2 447
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2012
    Messages : 2 447
    Points : 4 966
    Points
    4 966
    Par défaut Pagination d'une datagrid
    bonjour à tous et à toutes,

    je viens de débuter en c# et j'ai crée une Datagrid qui affiche les données d'une table sqlserver et je voudrais la paginer.

    la fonction c# :

    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    protected void NewPage(object b, DataGridPageChangedEventArgs c)
            {
                maGrille.CurrentPageIndex = c.NewPageIndex;
                maGrille.DataBind();
            }

    la page .aspx :

    Code aspx : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
     
    <body>
       <form id="form1" runat="server">
        <div id="divaff" runat="server">
        <asp:datagrid runat="server" id="maGrille" BackColor="Beige" CellPadding="4" 
                BorderColor="#000004" AllowPaging="True" OnPageIndexChanged="NewPage" 
                AllowCustomPaging="True" AllowSorting="True" PageSize="20" > 
            <HeaderStyle BackColor="Brown" ForeColor="White" Font-Bold="True" HorizontalAlign="Center"> 
            </HeaderStyle>   
            <AlternatingItemStyle BackColor="White" />
    	  <PagerStyle Mode="NumericPages" HorizontalAlign="Center" NextPageText="&gt;&gt;" 
                PrevPageText="&lt;&lt;" Position="TopAndBottom" />
          </asp:datagrid> 
        </div>
        <asp:Button ID="envoyer" Text="Afficher" runat=server OnClick="Afficher" /> 
        </form>
    </body>

    finalement la pagination ne s'applique que sur la première page de ma DataGrid, quelqu'un peut m'aider s'il vous plait?

  2. #2
    Expert confirmé Avatar de Toufik83
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2012
    Messages
    2 447
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2012
    Messages : 2 447
    Points : 4 966
    Points
    4 966
    Par défaut
    j'ai fais plusieurs modifications et j'ai utilisé DataAdapter et DataSet au lieu de DataReader mais rien ne fonctionne correctement.
    voila le code
    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
     
       int startIndex = 0;
       string myInsertQuery = "select distinct  Titre_cat as Titre, date_modif as Ladate  from categorie";
       DataSet Ds=new DataSet();
       SqlDataAdapter dataadapter;
     
        protected DataSet CreateDataSource()
        {
            SqlCommand myCommand = new SqlCommand(myInsertQuery, Connection);
            dataadapter = new SqlDataAdapter(myInsertQuery, Connection);
     
                dataadapter.Fill(Ds);
                Connection.Close();
                maGrille.DataSource = Ds.Tables[0];
                maGrille.DataBind();
        return Ds;
        }
        protected void MyDataGrid_Page(Object sender, DataGridPageChangedEventArgs e)
        {
           maGrille.CurrentPageIndex = e.NewPageIndex;
           startIndex = maGrille.CurrentPageIndex * maGrille.PageSize;
            BindGrid();
     
        }
        void BindGrid()
        {
     
            maGrille.DataSource = CreateDataSource().Tables[0];
            maGrille.DataBind();
     
        }
     
        protected void Page_Load(object sender, EventArgs e)
            {   //Connexion 
                Connection.Open();
                if (!Page.IsPostBack)
                {
                    maGrille.VirtualItemCount = 2000;
                    BindGrid();
                }
            }
    code de la page .aspx
    Code dot.net : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     
    <form id="form1" runat="server">
        <div id="divaff" runat="server">
        <asp:datagrid runat="server" id="maGrille" BackColor="Beige" CellPadding="4"
                BorderColor="#000004" OnPageIndexChanged="MyDataGrid_Page" AllowPaging="True"  
                AllowCustomPaging="True"  PageSize="20" AllowSorting="True"  > 
            <HeaderStyle BackColor="Brown" ForeColor="White" Font-Bold="True" HorizontalAlign="Center"> 
            </HeaderStyle>   
            <AlternatingItemStyle BackColor="White" />
    	  <PagerStyle Mode="NumericPages" HorizontalAlign="Center" NextPageText="&gt;&gt;" 
                PrevPageText="&lt;&lt;" Position="TopAndBottom" />
          </asp:datagrid> 
        </div>
        <asp:Button ID="envoyer" Text="Afficher" runat=server  /> 
        </form>

    les données de ma base SQL Server s'affiche mais la pagination ne s'effectue que sur la première page et même si je clique sur page 2 page 3... rien ne change, la liste reste fixe.
    quelqu'un peut m'aider s'il vous plait?

  3. #3
    Expert confirmé Avatar de Toufik83
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2012
    Messages
    2 447
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2012
    Messages : 2 447
    Points : 4 966
    Points
    4 966
    Par défaut
    pourquoi il n y a plus personne qui me réponds ?

  4. #4
    Expert confirmé

    Homme Profil pro
    Chef de projet NTIC
    Inscrit en
    Septembre 2006
    Messages
    3 580
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Chef de projet NTIC
    Secteur : Aéronautique - Marine - Espace - Armement

    Informations forums :
    Inscription : Septembre 2006
    Messages : 3 580
    Points : 5 194
    Points
    5 194
    Par défaut
    peut-etre qu'en cherchant sur Internet, tu trouverais la solution...

    Et puis, ici, nous sommes des bénévoles.. donc, si t'as pas de réponse, peut-être que ton sujet, soit n’intéresse pas les lecteurs, soit, tout simplement on considère
    (ou une partie des lecteurs) que la réponse ayant déjà été traités maintes fois, la réponse se trouvera via une recherche...

  5. #5
    Expert confirmé Avatar de Toufik83
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2012
    Messages
    2 447
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2012
    Messages : 2 447
    Points : 4 966
    Points
    4 966
    Par défaut
    j'arrête pas de faire des recherches et je tombe toujours sur les mêmes réponses c'est que je dois gérer l’événement OnPageIndexChanged de ma DataGrid asp.net.
    je l'ai mis dans mon code et j'ai fais toutes les manipulations possibles mais la liste n'affiche que la 1 ère page (la pagination n'a jamais fonctionné)

    en faite ça me parait logique que la liste n'affiche que la 1 ère page puisque on clique sur les numéros des pages, la page s'initialise et la fonction Page_Load(object sender, EventArgs e) renvois toujours la même requête SQL.



    bon je vous donne le code pour que se soit plus claire , espérant que vous compreniez mieux mon problème.

    page .aspx
    Code asp.net : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
     
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="~/Default.aspx.cs" Inherits="_Default" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server" >
    <link rel="Stylesheet" href="Styles/simplePagination.css" />
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
     <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
     <script type="text/javascript" src="Scripts/JScript.js" ></script>
     <script type="text/javascript" src="Scripts/jquery-1.4.1-vsdoc.js"></script>
     <script type="text/javascript" src="Scripts/PAGINATION/EasyPagination/jquery.simplePagination.js"></script>
        <title>BDD</title>
    </head>
    <body>
    <asp:Label id="indexpage" runat="server"></asp:Label>
       <form id="form1" runat="server">
        <div id="divaff" runat="server">
        <asp:datagrid runat="server" id="maGrille" CssClass="pagine" EnableViewState="true" Visible=true BackColor="Beige" CellPadding="4"
                BorderColor="#000004"  AllowPaging="True"  
                AllowCustomPaging="True"  PageSize="20" AllowSorting="True"  
                OnPageIndexChanged="MyDataGrid_Page"  ShowFooter="True" > 
            <Columns>
                <asp:EditCommandColumn CancelText="Annuler" EditText="Modifier" 
                    SortExpression="Trier" UpdateText="Mettre à jour"></asp:EditCommandColumn>
                <asp:ButtonColumn CommandName="Delete" Text="Supprimer"></asp:ButtonColumn>
            </Columns>
            <HeaderStyle BackColor="Brown" ForeColor="White" Font-Bold="True" HorizontalAlign="Center"> 
            </HeaderStyle>   
            <AlternatingItemStyle BackColor="White" />
    	  <PagerStyle CssClass="pagerstyle"  Mode="NumericPages" HorizontalAlign="Center" NextPageText="&gt;&gt;" 
                PrevPageText="&lt;&lt;" Position="TopAndBottom" />
          </asp:datagrid> 
        </div>
        <div id="contgridview" runat="server" style="background-color:Silver">
            <asp:GridView ID="maGridView" runat="server"></asp:GridView>
        </div>
        <asp:Button ID="envoyer" Text="Afficher" runat="server" OnClick="Afficher" OnClientClick="test();" /> 
        </form>
    <//body>
    </html>

    puis le code behind :
    Code C# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.Data;
    using System.Data.SqlClient;
    public partial class _Default : System.Web.UI.Page
    {
        //Declaration du reader
        SqlDataReader reader;
        //Declaration de la variable 
        SqlConnection Connection = new SqlConnection("Data Source=MONORDINATEUR\\SAM;Database=Base_2eme_Tache;User ID=sa;Password=sam");
        //Variable contenant la requète
        string myselectQuery = "select distinct  *  from categorie";
        DataSet Ds=new DataSet();
        SqlDataAdapter dataadapter=new SqlDataAdapter();
        DataView Dv = new DataView();
     
        protected void MyDataGrid_Page(Object sender, DataGridPageChangedEventArgs e)
        {
                maGrille.CurrentPageIndex = e.NewPageIndex;
                maGrille.DataSource = CreateDataSource();
     
        }
        protected DataSet CreateDataSource()
        {
            dataadapter = new SqlDataAdapter(myselectQuery, Connection);
                dataadapter.Fill(Ds);
                maGrille.DataSource = Ds.Tables[0];
                maGrille.DataBind();
     
        return Ds;
        }
        protected void Page_Load(object sender, EventArgs e)
            {   //Connexion 
                Connection.Open();
                maGrille.VirtualItemCount = 3000;
                if (! Page.IsPostBack)
                    {
                        maGrille.DataSource =CreateDataSource();
                    }
                Connection.Close();
            }
     
        protected void Afficher(object sender, EventArgs e)
            {
                Connection.Open();
                SqlCommand myCommand = new SqlCommand(myselectQuery, Connection);
                reader = myCommand.ExecuteReader();
                maGrille.DataSource = reader;
                maGrille.DataBind();
                //NewPage();
                reader.Close();
                Connection.Close();
            }
        protected void NewPage(object b, DataGridPageChangedEventArgs c)
            {
                SqlCommand myCommand = new SqlCommand(myselectQuery, Connection);
                reader = myCommand.ExecuteReader();
                maGrille.DataSource = reader;
                maGrille.CurrentPageIndex = c.NewPageIndex;
                maGrille.DataBind();
            }
        protected void NavigationButtonClick(object sender, System.EventArgs e)
        {
            string direction = ((Button)sender).CommandName;
     
            switch (direction.ToUpper())
            {
                case "FIRST":
                    maGrille.CurrentPageIndex = 0;
                    break;
                case "PREVIOUS":
                    maGrille.CurrentPageIndex =
                       Math.Max(maGrille.CurrentPageIndex - 1, 0);
                    break;
                case "NEXT":
                    maGrille.CurrentPageIndex =
                       Math.Min(maGrille.CurrentPageIndex + 1,
                       maGrille.PageCount - 1);
                    break;
                case "LAST":
                    maGrille.CurrentPageIndex = maGrille.PageCount - 1;
                    break;
                default:
                    break;
            }
            maGrille.DataBind();
        }
     
        }

  6. #6
    Expert confirmé Avatar de Toufik83
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Janvier 2012
    Messages
    2 447
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : Suisse

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Janvier 2012
    Messages : 2 447
    Points : 4 966
    Points
    4 966
    Par défaut
    ça y'est j'ai trouvé le petit détail qui faisait le bug (aucun article ou discussion qui mentionne ça), en faite il faut utiliser un GridView au lieu de datagrid.

    Code asp.net : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    <div id="contgridview" runat="server" style="background-color:Silver">
            <asp:GridView ID="maGridView" runat="server" AllowPaging="True" 
                AllowSorting="True" AutoGenerateDeleteButton="True" 
                AutoGenerateEditButton="True" AutoGenerateSelectButton="True" OnPageIndexChanging="MyDataView_Page">
            </asp:GridView>

    puis dans le code behind
    Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    protected void MyDataView_Page(Object sender2, GridViewPageEventArgs es)
        {
            maGridView.PageIndex = es.NewPageIndex;
            maGridView.DataSource = CreateDataSource();
        }

    NOTEZ BIEN : le déclencheur d’événement "OnPageIndexChanging" de l'élément GRIDVIEW est géré par "GridViewPageEventArgs", alors que le déclencheur d'événement
    "OnPageIndexChanged" de l'élément DataGrid est géré par "DataGridPageChangedEventArgs".

    c'est bizarre de ne pas trouver au moins une discussion qui mentionne cette information, voila j'espère que j'ai apporté quelque chose de nouveau.. peut être. Merci à vous.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Pagination d'une DataGrid
    Par Invité dans le forum Windows Presentation Foundation
    Réponses: 0
    Dernier message: 31/05/2011, 17h51
  2. Tri dans une datagrid paginée
    Par Asce. dans le forum Flex
    Réponses: 4
    Dernier message: 21/03/2010, 21h39
  3. Réponses: 7
    Dernier message: 12/02/2009, 10h55
  4. Pb d'update dans une DataGrid
    Par bidson dans le forum XMLRAD
    Réponses: 11
    Dernier message: 27/05/2003, 14h11

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo