Форум программистов, компьютерный форум, киберфорум
C# Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.86/7: Рейтинг темы: голосов - 7, средняя оценка - 4.86
3 / 3 / 3
Регистрация: 29.02.2016
Сообщений: 175

Ошибки при создании отчета по базе данных как исправить

23.07.2018, 14:40. Показов 1515. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Создаю отчет по базе данных, смотрел видео на ютубе ни у кого нет подобных ошибок, гооглил бесполезно.
приложение работает хорошо, подключено к базе данных MS SQL, заношу файлы в базу данных, вывожу в exel, создаю новую форму добавляю элемент reportViewer, pзахожу в ReportVizard, выбираю мою таблицу, добавляю. Отчет делаю первый раз
Миниатюры
Ошибки при создании отчета по базе данных как исправить   Ошибки при создании отчета по базе данных как исправить  
Вложения
Тип файла: rar проект GIK.rar (102.1 Кб, 2 просмотров)
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
23.07.2018, 14:40
Ответы с готовыми решениями:

У меня две ошибки по Базе данных: как мне их исправить
У меня две ошибки по Базе данных помогите мне пожалуйста их исправить заранее спасибо. 1.Индекс или ключ не может содержать...

Не могу исправить ошибки в базе данных Автомобили
Добрый день. Ребята мне сегодня пришел ответ по базам данных, часть ошибок я исправил, но сейчас новые появились. Не ясно как...

Краш при создании чекпоинта: найти и исправить ошибки в коде
RPC_CALLBACK CRPCCallback::SetPlayerCheckpointEx(RPC_ARGS) { CVector pos; float size; unsigned int col; unsigned short...

3
 Аватар для ViterAlex
8951 / 4863 / 1886
Регистрация: 11.02.2013
Сообщений: 10,246
23.07.2018, 18:35
Первые 4 ругаются на имена полей. Не должно быть пробелов, я так понимаю.
Остальные ругаются на ссылки из другого DataSet. Тут не знаю как исправить, но вот что советуют
0
3 / 3 / 3
Регистрация: 29.02.2016
Сообщений: 175
23.07.2018, 20:18  [ТС]
Разобрался не без вашей помощи, первые ошибки были в том что таблицы и столбцы базы данных были написаны по русски, первым делом вернул DataSet все верно оно на др DataSet ссылается, потом названия таблиц и столбцов написал по английски с пробелами снова были ошибки, вообщем вывод: нужно в MS SQL создавать таблицы и поля по англ и без пробелов, пока другого решения этой проблемы не нашел, либо будет куча ошибок
0
 Аватар для Kazbek17
1484 / 939 / 454
Регистрация: 06.02.2012
Сообщений: 2,868
24.07.2018, 18:13
Если нет других вариков. То вот класс для печати.
Кликните здесь для просмотра всего текста

C#
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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;
        }
    }
}

Затем в проекте создаешь глобальные переменные и описываешь методы с событием.
После нужно заполнить таблицу данными и нажать кнопку печать
C#
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
        DataGridViewPrinter print;
        PrintDocument MyPrintDocument = new PrintDocument();
        //Метод для печати
        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 = "Печать документа";
            MyPrintDocument.PrinterSettings = MyPrintDialog.PrinterSettings;
            MyPrintDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
            MyPrintDocument.DefaultPageSettings.Margins = new Margins(40, 40, 40, 40);
            //<----------------------------ГДЕ (dgv)- это твоя datagridView
            print = new DataGridViewPrinter(dgv, MyPrintDocument, true, true, "Данные", new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point), Color.Black, true);
 
            return true;
        }
        //Пред.просмотр
        private void MyPrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            bool more = print.DrawDataGridView(e.Graphics);
            if (more == true)
                e.HasMorePages = true;
        }
 
        //<---------------------Событие происходит при нажатие на кнопку (Печать)----------------------->
        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (SetupThePrinting())
            {
                PrintPreviewDialog MyPrintPreviewDialog = new PrintPreviewDialog();
                MyPrintPreviewDialog.Document = MyPrintDocument;
                MyPrintPreviewDialog.ShowDialog();
                MyPrintDocument.Print();
            }
 
        }
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
24.07.2018, 18:13
Помогаю со студенческими работами здесь

Как исправить ошибки при открытии базы данных в Qt в объекте tableView?
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work. ...

Ошибки при создании базы данных
Привет всем! Я написал такой код. &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Creating a Database&lt;/TITLE&gt; &lt;/HEAD&gt; &lt;?php // Установка значения...

Entity Framework. Ошибки при создании EntityModel из базы данных
Народ. Вот есть база данных Всё вроде нормально в ней составлено, но при создании модели данных вылетает несколько ошибок. не понять из-за...

При создании отчета с помощью Fast Report не получается выбрать datsourse, как быть?
в делфи при создание отчета с помощью Fast report, не получается выбрать datsourse, как быть?

Ошибки при подключении к базе данных MySQL
ОШИБКА Warning: mysql_connect() : Unknown MySQL server host 'hostingerru' (-2) in...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
Использование SDL3-callbacks вместо функции main() на Android, Desktop и WebAssembly
8Observer8 24.01.2026
Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а привычная функция main(). . .
моя боль
iceja 24.01.2026
Выложила интерполяцию кубическими сплайнами www. iceja. net REST сервисы временно не работают, только через Web. Написала за 56 рабочих часов этот сайт с нуля. При помощи perplexity. ai PRO , при. . .
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru