Модераторы: gambit
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Печать содержимого DataGridView, Печать 
V
    Опции темы
Doss
Дата 30.11.2008, 14:02 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 171
Регистрация: 5.10.2007

Репутация: нет
Всего: нет



Прочитал пару статей на англоязычных форумах, не совсем понял как печатать содержимое DataGridView, возможно кто сталкивался с подобной проблемой или схожой задачей? Подскажите желательно на примере, Заранее благодарен всем кто принял участие.
PM MAIL   Вверх
Nestap
Дата 30.11.2008, 16:29 (ссылка)   | (голосов:1) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 221
Регистрация: 10.10.2008

Репутация: 1
Всего: 0



Doss
интересня тема!

я посколько я понел нада работать с датасет! и соедининить с Crystal Reports но пока я етова не знаю!

может ктота поможет буду благадарен!
smile
--------------------
<?    echo "Nestap";?>
PM WWW ICQ Skype Jabber   Вверх
shmarov
Дата 2.12.2008, 12:19 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 70
Регистрация: 15.6.2007
Где: 1001101 region

Репутация: нет
Всего: 1



Рисуешь форму отчета в crystal-е, и потом подпихиваешь ему Source
поищи, на форуме поднималась тема
PM MAIL   Вверх
Doss
Дата 5.12.2008, 11:00 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 171
Регистрация: 5.10.2007

Репутация: нет
Всего: нет



Благодарен всем, буду искать, как решу что получилось, обязательно тут выложу на вашу критику.....Но вопрос пока в силе

Это сообщение отредактировал(а) Doss - 5.12.2008, 11:01
PM MAIL   Вверх
okaton
Дата 11.12.2008, 22:11 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 213
Регистрация: 24.11.2006

Репутация: нет
Всего: нет



Есть какие-то продвижения?
PM MAIL   Вверх
Doss
Дата 19.12.2008, 07:00 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 171
Регистрация: 5.10.2007

Репутация: нет
Всего: нет



продвижения только в том, что могу в отчет вывести данные уже записанные в базу и находящиеся в таблицу, но у меня данныые в дата сете, но не в базе. Хочу подсунуть ее в отчет, но не получается......если попробывать записать все данные в таблицу, а после в отчет, но это мыли на деле пока не начал...... У кого какие мысли? Nestap, может решение есть?
PM MAIL   Вверх
Nestap
Дата 19.12.2008, 07:07 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 221
Регистрация: 10.10.2008

Репутация: 1
Всего: 0



Doss

a podilisi kak ti danie iz bazi v reports...
;)
--------------------
<?    echo "Nestap";?>
PM WWW ICQ Skype Jabber   Вверх
musson
Дата 19.12.2008, 10:14 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 24
Регистрация: 28.9.2008

Репутация: нет
Всего: нет



тоже интересно))
но сам печатал токо с помощью printdocument
PM MAIL   Вверх
Doss
Дата 26.1.2009, 19:17 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 171
Регистрация: 5.10.2007

Репутация: нет
Всего: нет



musson, отправь пожалуйста пример как печатать, Nestap, извени, отправлю обяательно если еще актуален вопрос для тебя, но для меня это очень важно, было бы возможнось печатать из DataGridView, просто классно было бы!!! Может у кого-то есть такое решение?
PM MAIL   Вверх
antikom
Дата 27.1.2009, 11:45 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Новичок



Профиль
Группа: Участник
Сообщений: 39
Регистрация: 10.11.2008

Репутация: нет
Всего: 1



PM MAIL WWW ICQ Skype YIM   Вверх
Doss
Дата 27.1.2009, 19:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 171
Регистрация: 5.10.2007

Репутация: нет
Всего: нет



В общем то все получилось с печатью, все что нужно, это иметь класс типа:
Код

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Data;
using System.Windows.Forms;

class DataGridViewPrinter
{
    private DataGridView TheDataGridView; // The DataGridView Control which will be printed
    private PrintDocument ThePrintDocument; // The PrintDocument to be used for printing
    private bool IsCenterOnPage; // Determine if the report will be printed in the Top-Center of the page
    private bool IsWithTitle; // Determine if the page contain title text
    private string TheTitleText; // The title text to be printed in each page (if IsWithTitle is set to true)
    private Font TheTitleFont; // The font to be used with the title text (if IsWithTitle is set to true)
    private Color TheTitleColor; // The color to be used with the title text (if IsWithTitle is set to true)
    private bool IsWithPaging; // Determine if paging is used

    static int CurrentRow; // A static parameter that keep track on which Row (in the DataGridView control) that should be printed

    static int PageNumber;

    private int PageWidth;
    private int PageHeight;
    private int LeftMargin;
    private int TopMargin;
    private int RightMargin;
    private int BottomMargin;

    private float CurrentY; // A parameter that keep track on the y coordinate of the page, so the next object to be printed will start from this y coordinate

    private float RowHeaderHeight;
    private List<float> RowsHeight;
    private List<float> ColumnsWidth;
    private float TheDataGridViewWidth;
        
    // Maintain a generic list to hold start/stop points for the column printing
    // This will be used for wrapping in situations where the DataGridView will not fit on a single page
    private List<int[]> mColumnPoints;
    private List<float> mColumnPointsWidth;
    private int mColumnPoint;
        
    // The class constructor
    public DataGridViewPrinter(DataGridView aDataGridView, PrintDocument aPrintDocument, bool CenterOnPage, bool WithTitle, string aTitleText, Font aTitleFont, Color aTitleColor, bool WithPaging)
    {
        TheDataGridView = aDataGridView;
        ThePrintDocument = aPrintDocument;
        IsCenterOnPage = CenterOnPage;
        IsWithTitle = WithTitle;
        TheTitleText = aTitleText;
        TheTitleFont = aTitleFont;
        TheTitleColor = aTitleColor;
        IsWithPaging = WithPaging;

        PageNumber = 0;

        RowsHeight = new List<float>();
        ColumnsWidth = new List<float>();

        mColumnPoints = new List<int[]>();
        mColumnPointsWidth = new List<float>();

        // Claculating the PageWidth and the PageHeight
        if (!ThePrintDocument.DefaultPageSettings.Landscape)
        {
            PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }
        else
        {
            PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Width;
            PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Height;
        }

        // Claculating the page margins
        LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left;
        TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top;
        RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right;
        BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom;

        // First, the current row to be printed is the first row in the DataGridView control
        CurrentRow = 0;
    }

    // The function that calculate the height of each row (including the header row), the width of each column (according to the longest text in all its cells including the header cell), and the whole DataGridView width
    private void Calculate(Graphics g)
    {
        if (PageNumber == 0) // Just calculate once
        {
            SizeF tmpSize = new SizeF();
            Font tmpFont;
            float tmpWidth;

            TheDataGridViewWidth = 0;
            for (int i = 0; i < TheDataGridView.Columns.Count; i++)
            {
                tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
                if (tmpFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
                    tmpFont = TheDataGridView.DefaultCellStyle.Font;

                tmpSize = g.MeasureString(TheDataGridView.Columns[i].HeaderText, tmpFont);
                tmpWidth = tmpSize.Width;
                RowHeaderHeight = tmpSize.Height;

                for (int j = 0; j < TheDataGridView.Rows.Count; j++)
                {
                    tmpFont = TheDataGridView.Rows[j].DefaultCellStyle.Font;
                    if (tmpFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
                        tmpFont = TheDataGridView.DefaultCellStyle.Font;

                    tmpSize = g.MeasureString("Anything", tmpFont);
                    RowsHeight.Add(tmpSize.Height);

                    tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont);
                    if (tmpSize.Width > tmpWidth)
                        tmpWidth = tmpSize.Width;
                }
                if (TheDataGridView.Columns[i].Visible)
                    TheDataGridViewWidth += tmpWidth;
                ColumnsWidth.Add(tmpWidth);
            }

            // Define the start/stop column points based on the page width and the DataGridView Width
            // We will use this to determine the columns which are drawn on each page and how wrapping will be handled
            // By default, the wrapping will occurr such that the maximum number of columns for a page will be determine
            int k;

            int mStartPoint = 0;
            for (k = 0; k < TheDataGridView.Columns.Count; k++)
                if (TheDataGridView.Columns[k].Visible)
                {
                    mStartPoint = k;
                    break;
                }

            int mEndPoint = TheDataGridView.Columns.Count;
            for (k = TheDataGridView.Columns.Count - 1; k >= 0; k--)
                if (TheDataGridView.Columns[k].Visible)
                {
                    mEndPoint = k + 1;
                    break;
                }

            float mTempWidth = TheDataGridViewWidth;
            float mTempPrintArea = (float)PageWidth - (float)LeftMargin - (float)RightMargin;
            
            // We only care about handling where the total datagridview width is bigger then the print area
            if (TheDataGridViewWidth > mTempPrintArea)
            {
                mTempWidth = 0.0F;
                for (k = 0; k < TheDataGridView.Columns.Count; k++)
                {
                    if (TheDataGridView.Columns[k].Visible)
                    {
                        mTempWidth += ColumnsWidth[k];
                        // If the width is bigger than the page area, then define a new column print range
                        if (mTempWidth > mTempPrintArea)
                        {
                            mTempWidth -= ColumnsWidth[k];
                            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
                            mColumnPointsWidth.Add(mTempWidth);
                            mStartPoint = k;
                            mTempWidth = ColumnsWidth[k];
                        }
                    }
                    // Our end point is actually one index above the current index
                    mEndPoint = k + 1;
                }
            }
            // Add the last set of columns
            mColumnPoints.Add(new int[] { mStartPoint, mEndPoint });
            mColumnPointsWidth.Add(mTempWidth);
            mColumnPoint = 0;
        }
    }

    // The funtion that print the title, page number, and the header row
    private void DrawHeader(Graphics g)
    {
        CurrentY = (float)TopMargin;

        // Printing the page number (if isWithPaging is set to true)
        if (IsWithPaging)
        {
            PageNumber++;
            string PageString = "Page " + PageNumber.ToString();

            StringFormat PageStringFormat = new StringFormat();
            PageStringFormat.Trimming = StringTrimming.Word;
            PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            PageStringFormat.Alignment = StringAlignment.Far;

            Font PageStringFont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point);

            RectangleF PageStringRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(PageString, PageStringFont).Height);

            g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat);

            CurrentY += g.MeasureString(PageString, PageStringFont).Height;
        }

        // Printing the title (if IsWithTitle is set to true)
        if (IsWithTitle)
        {
            StringFormat TitleFormat = new StringFormat();
            TitleFormat.Trimming = StringTrimming.Word;
            TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
            if (IsCenterOnPage)
                TitleFormat.Alignment = StringAlignment.Center;
            else
                TitleFormat.Alignment = StringAlignment.Near;

            RectangleF TitleRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(TheTitleText, TheTitleFont).Height);

            g.DrawString(TheTitleText, TheTitleFont, new SolidBrush(TheTitleColor), TitleRectangle, TitleFormat);

            CurrentY += g.MeasureString(TheTitleText, TheTitleFont).Height;
        }

        // Calculating the starting x coordinate that the printing process will start from
        float CurrentX = (float)LeftMargin;
        if (IsCenterOnPage)            
            CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;

        // Setting the HeaderFore style
        Color HeaderForeColor = TheDataGridView.ColumnHeadersDefaultCellStyle.ForeColor;
        if (HeaderForeColor.IsEmpty) // If there is no special HeaderFore style, then use the default DataGridView style
            HeaderForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
        SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor);

        // Setting the HeaderBack style
        Color HeaderBackColor = TheDataGridView.ColumnHeadersDefaultCellStyle.BackColor;
        if (HeaderBackColor.IsEmpty) // If there is no special HeaderBack style, then use the default DataGridView style
            HeaderBackColor = TheDataGridView.DefaultCellStyle.BackColor;
        SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor);

        // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
        Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);

        // Setting the HeaderFont style
        Font HeaderFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font;
        if (HeaderFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style
            HeaderFont = TheDataGridView.DefaultCellStyle.Font;

        // Calculating and drawing the HeaderBounds        
        RectangleF HeaderBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowHeaderHeight);
        g.FillRectangle(HeaderBackBrush, HeaderBounds);

        // Setting the format that will be used to print each cell of the header row
        StringFormat CellFormat = new StringFormat();
        CellFormat.Trimming = StringTrimming.Word;
        CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip;

        // Printing each visible cell of the header row
        RectangleF CellBounds;
        float ColumnWidth;        
        for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++)
        {
            if (!TheDataGridView.Columns[i].Visible) continue; // If the column is not visible then ignore this iteration

            ColumnWidth = ColumnsWidth[i];

            // Check the CurrentCell alignment and apply it to the CellFormat
            if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right"))
                CellFormat.Alignment = StringAlignment.Far;
            else if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center"))
                CellFormat.Alignment = StringAlignment.Center;
            else
                CellFormat.Alignment = StringAlignment.Near;

            CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);

            // Printing the cell text
            g.DrawString(TheDataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat);

            // Drawing the cell bounds
            if (TheDataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None) // Draw the cell border only if the HeaderBorderStyle is not None
                g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowHeaderHeight);

            CurrentX += ColumnWidth;
        }

        CurrentY += RowHeaderHeight;
    }

    // The function that print a bunch of rows that fit in one page
    // When it returns true, meaning that there are more rows still not printed, so another PagePrint action is required
    // When it returns false, meaning that all rows are printed (the CureentRow parameter reaches the last row of the DataGridView control) and no further PagePrint action is required
    private bool DrawRows(Graphics g)
    {
        // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control)
        Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1);

        // The style paramters that will be used to print each cell
        Font RowFont;
        Color RowForeColor;
        Color RowBackColor;
        SolidBrush RowForeBrush;
        SolidBrush RowBackBrush;
        SolidBrush RowAlternatingBackBrush;

        // Setting the format that will be used to print each cell
        StringFormat CellFormat = new StringFormat();
        CellFormat.Trimming = StringTrimming.Word;
        CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit;

        // Printing each visible cell
        RectangleF RowBounds;
        float CurrentX;
        float ColumnWidth;
        while (CurrentRow < TheDataGridView.Rows.Count)
        {
            if (TheDataGridView.Rows[CurrentRow].Visible) // Print the cells of the CurrentRow only if that row is visible
            {
                // Setting the row font style
                RowFont = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.Font;
                if (RowFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control
                    RowFont = TheDataGridView.DefaultCellStyle.Font;

                // Setting the RowFore style
                RowForeColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.ForeColor;
                if (RowForeColor.IsEmpty) // If the there is no special RowFore style of the CurrentRow, then use the default one associated with the DataGridView control
                    RowForeColor = TheDataGridView.DefaultCellStyle.ForeColor;
                RowForeBrush = new SolidBrush(RowForeColor);

                // Setting the RowBack (for even rows) and the RowAlternatingBack (for odd rows) styles
                RowBackColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.BackColor;
                if (RowBackColor.IsEmpty) // If the there is no special RowBack style of the CurrentRow, then use the default one associated with the DataGridView control
                {
                    RowBackBrush = new SolidBrush(TheDataGridView.DefaultCellStyle.BackColor);
                    RowAlternatingBackBrush = new SolidBrush(TheDataGridView.AlternatingRowsDefaultCellStyle.BackColor);
                }
                else // If the there is a special RowBack style of the CurrentRow, then use it for both the RowBack and the RowAlternatingBack styles
                {
                    RowBackBrush = new SolidBrush(RowBackColor);
                    RowAlternatingBackBrush = new SolidBrush(RowBackColor);
                }

                // Calculating the starting x coordinate that the printing process will start from
                CurrentX = (float)LeftMargin;
                if (IsCenterOnPage)                    
                    CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F;

                // Calculating the entire CurrentRow bounds                
                RowBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowsHeight[CurrentRow]);

                // Filling the back of the CurrentRow
                if (CurrentRow % 2 == 0)
                    g.FillRectangle(RowBackBrush, RowBounds);
                else
                    g.FillRectangle(RowAlternatingBackBrush, RowBounds);

                // Printing each visible cell of the CurrentRow                
                for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++)
                {
                    if (!TheDataGridView.Columns[CurrentCell].Visible) continue; // If the cell is belong to invisible column, then ignore this iteration

                    // Check the CurrentCell alignment and apply it to the CellFormat
                    if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Right"))
                        CellFormat.Alignment = StringAlignment.Far;
                    else if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Center"))
                        CellFormat.Alignment = StringAlignment.Center;
                    else
                        CellFormat.Alignment = StringAlignment.Near;
                    
                    ColumnWidth = ColumnsWidth[CurrentCell];
                    RectangleF CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]);

                    // Printing the cell text
                    g.DrawString(TheDataGridView.Rows[CurrentRow].Cells[CurrentCell].EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat);
                    
                    // Drawing the cell bounds
                    if (TheDataGridView.CellBorderStyle != DataGridViewCellBorderStyle.None) // Draw the cell border only if the CellBorderStyle is not None
                        g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]);

                    CurrentX += ColumnWidth;
                }
                CurrentY += RowsHeight[CurrentRow];

                // Checking if the CurrentY is exceeds the page boundries
                // If so then exit the function and returning true meaning another PagePrint action is required
                if ((int)CurrentY > (PageHeight - TopMargin - BottomMargin))
                {
                    CurrentRow++;
                    return true;
                }
            }
            CurrentRow++;
        }

        CurrentRow = 0;
        mColumnPoint++; // Continue to print the next group of columns

        if (mColumnPoint == mColumnPoints.Count) // Which means all columns are printed
        {
            mColumnPoint = 0;
            return false;
        }
        else
            return true;
    }

    // The method that calls all other functions
    public bool DrawDataGridView(Graphics g)
    {
        try
        {
            Calculate(g);
            DrawHeader(g);
            bool bContinue = DrawRows(g);
            return bContinue;
        }
        catch (Exception ex)
        {
            MessageBox.Show("Operation failed: " + ex.Message.ToString(), Application.ProductName + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return false;
        }
    }
}



а печать осуществлять так
Код

 private bool SetupThePrinting()
        {
            PrintDialog MyPrintDialog = new PrintDialog();
            MyPrintDialog.AllowCurrentPage = false;
            MyPrintDialog.AllowPrintToFile = false;
            MyPrintDialog.AllowSelection = false;
            MyPrintDialog.AllowSomePages = false;
            MyPrintDialog.PrintToFile = false;
            MyPrintDialog.ShowHelp = false;
            MyPrintDialog.ShowNetwork = false;

            if (MyPrintDialog.ShowDialog() != DialogResult.OK)
                return false;

            MyPrintDocument.DocumentName = this.Text;
            MyPrintDocument.PrinterSettings =
                                MyPrintDialog.PrinterSettings;
            MyPrintDocument.DefaultPageSettings =
            MyPrintDialog.PrinterSettings.DefaultPageSettings;
            MyPrintDocument.DefaultPageSettings.Landscape = true;
            MyPrintDocument.DefaultPageSettings.Margins =
                             new Margins(30, 30, 30, 30);

            MyDataGridViewPrinter = new DataGridViewPrinter(dataGridView1,
            MyPrintDocument, true, true, this.Text + " " + toolStripLabel2.Text + " : " + toolStripLabel3.Text, new Font("Tahoma", 8,
                FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);

            return true;
        }



обработчик принта прицепленного или обявленного вот так
Код

 private void MyPrintDocument_PrintPage(object sender,
            System.Drawing.Printing.PrintPageEventArgs e)
        {
            bool more = MyDataGridViewPrinter.DrawDataGridView(e.Graphics);
            if (more == true)
                e.HasMorePages = true;
        }



MyDataGridViewPrinter-это экземпляр класса

Весь код нашел на форуме SQL.RU

НУ а вообще нашел классную бибиаотеку, но взломать бы ее, вот класс был бы. Уважаемые программисты, если вам известно как его актвизировать подскажите, уж больно универсальная прога Teroid Data Grid View Print Control
Вот приклеплена она, распакуйте и пользуйтесь, но!!!! Прошу всех отозваться ....


Присоединённый файл ( Кол-во скачиваний: 18 )
Присоединённый файл  datagridviewprintcontrol.exe 426,00 Kb
PM MAIL   Вверх
Doss
Дата 27.1.2009, 19:38 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 171
Регистрация: 5.10.2007

Репутация: нет
Всего: нет



Кстати, есть второй вариант, можно вот так распечатать
Код

 string[] report = new string[dt.Rows.Count+10];
            report[0] = "<body><b><font size=4>"+title+"</font></b>";
            report[1] = "<table border=1 font=2><tr>";
            for (int j = 0; j < this.GVresult.ColumnCount; j++)
            {
                report[1] += "<td>"+this.GVresult.Columns[j].HeaderText+"</td>";
            }
            report[1] += "</tr>";

            int i = 2;
            for (; i < dt.Rows.Count + 2; i++)
            {
                report[i] = "<tr>";
                report[i] += "<td width=200 align=left>" + dt.Rows[i - 2][vf].ToString() + "</td>";
                for (int j = 0; j < dt.Columns.Count-3; j++)
                {
                    report[i] += "<td width=80 align=right>" + dt.Rows[i-2][j+1].ToString() + "</td>";
                }
                report[i] += "</tr>";
            }
            report[i+1] = "</table></body>";
            StreamWriter sr = new StreamWriter(Application.UserAppDataPath+"\\report.html");
            for (int j=0; j< report.Length; j++)
            {
                sr.Write(report[j]);
            }
            sr.Close();
            Process.Start("excel.exe",@"/r """ +Application.UserAppDataPath + @"\report.html""");



Добавлено через 1 минуту и 47 секунд
Помогите с кряком к библиотеке Teroid Data Grid View Print Control
Всем благодарен за участие

Присоединённый файл ( Кол-во скачиваний: 10 )
Присоединённый файл  datagridviewprintcontrol.exe 426,00 Kb
PM MAIL   Вверх
Doss
Дата 31.1.2009, 08:19 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 171
Регистрация: 5.10.2007

Репутация: нет
Всего: нет



Мож.... кто нашел как ее укратить, я про эту прогу Teroid Data Grid View Print Control, коментарии жду??????
Вот с классом проблемы, все печатает, но если вполе достаточно большой текс, то он тк в одну и линию печатается, как бы соранить размеры таблицы Грида, чтобы как вижу так и распечатываю.....знаю что что то в классе, но что иенно не могу разобраться..
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
stab
mr.DUDA
Exception

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, stab, mr.DUDA, Exception.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Базы данных под .NET | Следующая тема »


 




[ Время генерации скрипта: 0.0807 ]   [ Использовано запросов: 21 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.