Bouton imprimer DataGridView Complet

Résolu
Dorsaf Ouersighni - 26 janv. 2016 à 10:44
 Dorsaf Ouersighni - 28 janv. 2016 à 11:31
Bonjour,
bonjour à Tous,
sa fait longtemps que je cherche du code pour imprimer mon DataGridView complet avec visual basic 2010 express et j'ai testé tous les codes qu'ils s'affichent avec des recherches sur google mais en vain.
Mais finalement, j'ai trouver un code c# que j'ai converti en VB qui me convient parfaitement mais le seul problème c qu'il boucle infiniment ( boucle infini au niveau du nombre de pages )
NB: Le code ne génère aucune erreur
Voici mon code :
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Try
            Dim iHeaderHeight As Double
            'Set the left margin
            Dim iLeftMargin As Integer = e.MarginBounds.Left
            'Set the top margin
            Dim iTopMargin As Integer = e.MarginBounds.Top
            'Whether more pages have to print or not
            Dim bMorePagesToPrint As Boolean = False
            Dim iTmpWidth As Integer = 0
            'For the first page to print set the cell width and header height
            If bFirstPage Then
                For Each GridCol As DataGridViewColumn In DataGridView_impot.Columns
                    iTmpWidth = CType(Math.Floor(CType((CType(GridCol.Width, Double) / (CType(iTotalWidth, Double) * (CType(iTotalWidth, Double) * (CType(e.MarginBounds.Width, Double) / CType(iTotalWidth, Double))))), Double)), Integer)
                    iHeaderHeight = (CType(e.Graphics.MeasureString(GridCol.HeaderText, GridCol.InheritedStyle.Font, iTmpWidth).Height, Integer) + 11)
                    ' Save width and height of headers
                    arrColumnLefts.Add(iLeftMargin)
                    arrColumnWidths.Add(iTmpWidth)
                    iLeftMargin = (iLeftMargin + iTmpWidth)
                Next
            End If
 
            'Loop till all the grid rows not get printed
            Dim iRow As Double
            While (iRow <= (DataGridView_impot.Rows.Count - 1))
                Dim GridRow As DataGridViewRow = DataGridView_impot.Rows(iRow)
                'Set the cell height
                iCellHeight = (GridRow.Height + 5)
                Dim iCount As Integer = 0
                'Check whether the current page settings allows more rows to print
                If (iTopMargin + (iCellHeight >= (e.MarginBounds.Height + e.MarginBounds.Top))) Then
                    bNewPage = True
                    bFirstPage = False
                    bMorePagesToPrint = True
                    Exit While
                Else
                    If bNewPage Then
                        'Draw Header => raison sociale
                        e.Graphics.DrawString(Me.lbl_rs.Text, New Font(DataGridView_impot.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, (e.MarginBounds.Top - (e.Graphics.MeasureString(Me.lbl_rs.Text, New Font(DataGridView_impot.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)))
                        'Draw Date => date system
                        e.Graphics.DrawString(Me.lbl_date_now.Text, New Font(DataGridView_impot.Font, FontStyle.Bold), Brushes.Black, (e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(Me.lbl_date_now.Text, New Font(DataGridView_impot.Font, FontStyle.Bold), e.MarginBounds.Width).Width)), (e.MarginBounds.Top - (e.Graphics.MeasureString(Me.lbl_rs.Text, New Font(New Font(DataGridView_impot.Font, FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13)))
                        'Draw Columns                 
                        iTopMargin = e.MarginBounds.Top
                        For Each GridCol As DataGridViewColumn In DataGridView_impot.Columns
                            e.Graphics.FillRectangle(New SolidBrush(Color.LightGray), New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight))
                            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight))
                            e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font, New SolidBrush(GridCol.InheritedStyle.ForeColor), New RectangleF(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight), strFormat)
                            iCount = (iCount + 1)
                        Next
                        bNewPage = False
                        iTopMargin = (iTopMargin + iHeaderHeight)
                    End If
 
                    iCount = 0
                    'Draw Columns Contents
                    For Each Cel As DataGridViewCell In GridRow.Cells
                        If (Not (Cel.Value) Is Nothing) Then
                            e.Graphics.DrawString(Cel.Value.ToString, Cel.InheritedStyle.Font, New SolidBrush(Cel.InheritedStyle.ForeColor), New RectangleF(CType(arrColumnLefts(iCount), Integer), CType(iTopMargin, Single), CType(arrColumnWidths(iCount), Integer), CType(iCellHeight, Single)), strFormat)
                        End If
 
                        'Drawing Cells Borders 
                        e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iCellHeight))
                        iCount = (iCount + 1)
                    Next
                End If
 
                iRow = (iRow + 1)
                iTopMargin = (iTopMargin + iCellHeight)
 
            End While
 
            'If more lines exist, print another page.
            If bMorePagesToPrint Then
                e.HasMorePages = True
            Else
                e.HasMorePages = False
            End If
 
        Catch exc As Exception
            MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
 
 
    End Sub

3 réponses

Whismeril Messages postés 19026 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 20 avril 2024 656
Modifié par Whismeril le 26/01/2016 à 16:38
Bonjour,

peux tu mettre le code original en C#?

Quand j'étais petit, la mer Morte n'était que malade.
George Burns
1
Dorsaf Ouersighni
26 janv. 2016 à 16:43
private void printDocument1_PrintPage(object sender,
    System.Drawing.Printing.PrintPageEventArgs e)
{
    try
    {
        //Set the left margin
        int iLeftMargin = e.MarginBounds.Left;
        //Set the top margin
        int iTopMargin = e.MarginBounds.Top;
        //Whether more pages have to print or not
        bool bMorePagesToPrint = false;
        int iTmpWidth = 0;             

        //For the first page to print set the cell width and header height
        if (bFirstPage)
        {
            foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
            {
                iTmpWidth = (int)(Math.Floor((double)((double)GridCol.Width /
                    (double)iTotalWidth * (double)iTotalWidth *
                    ((double)e.MarginBounds.Width / (double)iTotalWidth))));

                iHeaderHeight = (int)(e.Graphics.MeasureString(GridCol.HeaderText,
                    GridCol.InheritedStyle.Font, iTmpWidth).Height) + 11;

                // Save width and height of headers
                arrColumnLefts.Add(iLeftMargin);
                arrColumnWidths.Add(iTmpWidth);
                iLeftMargin += iTmpWidth;
            }
        }
        //Loop till all the grid rows not get printed
        while (iRow <= dataGridView1.Rows.Count - 1)
        {
            DataGridViewRow GridRow = dataGridView1.Rows[iRow];
            //Set the cell height
            iCellHeight = GridRow.Height + 5;
            int iCount = 0;
            //Check whether the current page settings allows more rows to print
            if (iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
            {
                bNewPage = true;
                bFirstPage = false;
                bMorePagesToPrint = true;
                break;
            }
            else
            {
                if (bNewPage)
                {
                    //Draw Header
                    e.Graphics.DrawString("Customer Summary", 
                        new Font(dataGridView1.Font, FontStyle.Bold),
                        Brushes.Black, e.MarginBounds.Left, 
                        e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary",
                        new Font(dataGridView1.Font,FontStyle.Bold),
                        e.MarginBounds.Width).Height - 13);

                    String strDate = DateTime.Now.ToLongDateString() + " " +
                        DateTime.Now.ToShortTimeString();
                    //Draw Date
                    e.Graphics.DrawString(strDate, 
                        new Font(dataGridView1.Font, FontStyle.Bold), Brushes.Black,
                        e.MarginBounds.Left + 
                        (e.MarginBounds.Width - e.Graphics.MeasureString (strDate, 
                        new Font(dataGridView1.Font, FontStyle.Bold),
                        e.MarginBounds.Width).Width), 
                        e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary",
                        new Font(new Font(dataGridView1.Font, FontStyle.Bold), 
                        FontStyle.Bold), e.MarginBounds.Width).Height - 13);

                    //Draw Columns                 
                    iTopMargin = e.MarginBounds.Top;
                    foreach (DataGridViewColumn GridCol in dataGridView1.Columns)
                    {
                        e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),    
                            new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            (int)arrColumnWidths[iCount], iHeaderHeight));

                        e.Graphics.DrawRectangle(Pens.Black,             
                            new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                            (int)arrColumnWidths[iCount], iHeaderHeight));

                        e.Graphics.DrawString(GridCol.HeaderText,
                            GridCol.InheritedStyle.Font,
                            new SolidBrush(GridCol.InheritedStyle.ForeColor),
                            new RectangleF((int)arrColumnLefts[iCount], iTopMargin,
                            (int)arrColumnWidths[iCount], iHeaderHeight), strFormat);
                        iCount++;
                    }
                    bNewPage = false;
                    iTopMargin += iHeaderHeight;
                }
                iCount = 0;
                //Draw Columns Contents                
                foreach (DataGridViewCell Cel in GridRow.Cells)
                {
                    if (Cel.Value != null)
                    {
                        e.Graphics.DrawString(Cel.Value.ToString(),
                            Cel.InheritedStyle.Font,
                            new SolidBrush(Cel.InheritedStyle.ForeColor),
                            new RectangleF((int)arrColumnLefts[iCount],
                            (float)iTopMargin,
                            (int)arrColumnWidths[iCount], (float)iCellHeight),
                            strFormat);
                    }
                    //Drawing Cells Borders 
                    e.Graphics.DrawRectangle(Pens.Black, 
                        new Rectangle((int)arrColumnLefts[iCount], iTopMargin,
                        (int)arrColumnWidths[iCount], iCellHeight)); 
                    iCount++;
                }
            }
            iRow++;
            iTopMargin += iCellHeight;                    
        }        
        //If more lines exist, print another page.
        if (bMorePagesToPrint)
            e.HasMorePages = true;
        else
            e.HasMorePages = false;
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK,
           MessageBoxIcon.Error);
    }
}
0
Dorsaf Ouersighni
26 janv. 2016 à 16:56
Bonjour,
Mon problème est résolu concernant ma boucle infinie. Mais maintenant mon problème c que mon DataGridView est mal organisé dans l'impression; Toutes les colonnes s'écrivent dans une seule colonne de tel sorte que l'écriture est combinée.
0
Whismeril Messages postés 19026 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 20 avril 2024 656
26 janv. 2016 à 18:59
Y'a 50 variables, on ne sait pas d'ou elles sortent, quel est le contenu, etc...
On veut bien essayer de dépanner, mais pas faire de la voyance....

Si tu copies ce code dans un projet neuf, regarde tout ce qui se souligne en rouge, et reviens ici le décrire.
0
Dorsaf Ouersighni
27 janv. 2016 à 09:19
Bonjour,
Merci pour la réponse mais j'ai déclaré toutes les variables et je n'ai aucune erreur, rien n'est souligné en rouge. En plus j'ai résolu mon premier problème de boucle infini ; c'était juste une parenthèse mal placé dans la conversion.
Mon pèsent problème est que le DGV est mal organisé dans l'impression
0
Whismeril Messages postés 19026 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 20 avril 2024 656
Modifié par Whismeril le 27/01/2016 à 09:37
Oui, mais chez moi, pour tester les variables ne sont pas déclarées.
Je ne suis pas extralucide, donc pour trouver le bug, j'ai besoin de ces variables, sinon impossible de t'aider.
0
Whismeril Messages postés 19026 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 20 avril 2024 656
27 janv. 2016 à 20:18
Bonsoir,

tout d'abord, je t'invite à décocher l'import à Visual Basic dans les références, voici un exemple avec VS2013


Ça évitera d'avoir accès à des fonctions issues de VB6, voir cet article pour plus d'infos http://codes-sources.commentcamarche.net/faq/11151-pourquoi-mon-code-vb6-vba-ne-marche-pas-en-vb-net

Par conséquent, cette ligne ne fonctionnera plus
        Dim r As String = CStr(MsgBox("Etes vous sûre de vouloir imprimer cette page ?", CType(vbQuestion + vbYesNo +
        vbDefaultButton2, MsgBoxStyle)))
        If CDbl(r) <> vbYes Then Exit Sub


à remplacer par
        If (MessageBox.Show("Etes vous sûr de vouloir imprimer cette page ?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No) Then Exit Sub
0
Dorsaf Ouersighni
28 janv. 2016 à 09:27
Bonjour,
Merci Whismeril. Je vais esseyer votre solution
0
Whismeril Messages postés 19026 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 20 avril 2024 656
Modifié par Whismeril le 27/01/2016 à 20:39
Cette ligne retourne toujours 0
iTmpWidth = CType(Math.Floor(CType((CType(GridCol.Width, Double) / (CType(iTotalWidth, Double) * (CType(iTotalWidth, Double) * (CType(e.MarginBounds.Width, Double) / CType(iTotalWidth, Double))))), Double)), Integer)


alors que son homologue C#, avec les variables identiques retourne 209, 411, etc.... (d'ou l'intérêt de connaitre le contenu.....)
Voici une traduction "brute" qui retourne la même chose que le code C#
iTmpWidth = CInt((Math.Floor(CDbl(CDbl(GridCol.Width) / CDbl(iTotalWidth) * CDbl(iTotalWidth) * (CDbl(e.MarginBounds.Width) / CDbl(iTotalWidth))))))


Par contre, ca me parait un peu tordu comme calcul:
a/b*b*c/b, au final ça devait faire a * c / b

Ça se résume donc
iTmpWidth = CInt(CDbl(GridCol.Width) * CDbl(e.MarginBounds.Width) / CDbl(iTotalWidth))


Là le tableau s'imprime correctement, par contre les labels sont masqués.

Te les faut-ils aussi?

Quand j'étais petit, la mer Morte n'était que malade.
George Burns
0
Dorsaf Ouersighni
28 janv. 2016 à 09:30
Oui jai besoin des labels aussi
Merci beaucoup pour ton aide :)
0
Dorsaf Ouersighni
28 janv. 2016 à 10:52
C pas grave pour les Labels. j'ai résolu mon problème grâce à vous.
Vraiment MERCIIIIIII beaucoup
0
Whismeril Messages postés 19026 Date d'inscription mardi 11 mars 2003 Statut Contributeur Dernière intervention 20 avril 2024 656
28 janv. 2016 à 11:10
Alors pense à mettre le sujet résolu avec le lien dédié sous le titre de la discussion
0
Dorsaf_Ouersighni Messages postés 1 Date d'inscription mardi 26 janvier 2016 Statut Membre Dernière intervention 28 janvier 2016
28 janv. 2016 à 11:25
D'accord
0
J'arrive pas à le mettre comme Résolu :/
Peut-être parce que je l'ai posté avant de se connecter
0
Rejoignez-nous