Загрузка данных
using System;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class FormReport : Form
{
private DataTable reportData;
private int printRowIndex = 0; // текущая строка при печати
public FormReport()
{
InitializeComponent();
LoadData();
btnPreview.Click += BtnPreview_Click;
printDocument1.PrintPage += PrintDocument1_PrintPage;
}
private void LoadData()
{
// Загружаем отчёт: продажи с деталями
reportData = DbHelper.GetTable(
@"SELECT s.ID AS [№],
CONVERT(VARCHAR, s.SaleDate, 104) AS [Дата],
c.LastName + ' ' + c.FirstName AS [Клиент],
e.LastName + ' ' + e.FirstName AS [Сотрудник],
SUM(sd.Quantity * sd.SalePrice) AS [Сумма]
FROM Sales s
JOIN Clients c ON s.ClientID = c.ID
JOIN Employees e ON s.EmployeeID = e.ID
JOIN SaleDetails sd ON s.ID = sd.SaleID
GROUP BY s.ID, s.SaleDate, c.LastName, c.FirstName, e.LastName, e.FirstName
ORDER BY s.SaleDate DESC");
dgv.DataSource = reportData;
}
private void BtnPreview_Click(object sender, EventArgs e)
{
printRowIndex = 0; // сброс перед каждым предпросмотром
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
private void PrintDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Graphics g = e.Graphics;
Font fontTitle = new Font("Arial", 14, FontStyle.Bold);
Font fontHeader = new Font("Arial", 10, FontStyle.Bold);
Font fontCell = new Font("Arial", 9);
Brush brush = Brushes.Black;
int x = 40, y = 40;
int pageWidth = e.MarginBounds.Width;
// Заголовок отчёта
g.DrawString("Отчёт по продажам", fontTitle, brush, x, y);
y += 30;
g.DrawString("Дата: " + DateTime.Now.ToString("dd.MM.yyyy"), fontCell, brush, x, y);
y += 25;
g.DrawLine(Pens.Black, x, y, x + pageWidth, y);
y += 10;
// Ширины колонок
int[] colWidths = { 40, 80, 160, 160, 80 };
// Шапка таблицы
int cx = x;
foreach (DataColumn col in reportData.Columns)
{
int idx = reportData.Columns.IndexOf(col);
g.DrawString(col.ColumnName, fontHeader, brush, cx, y);
cx += colWidths[idx];
}
y += 20;
g.DrawLine(Pens.Black, x, y, x + pageWidth, y);
y += 5;
// Строки данных
while (printRowIndex < reportData.Rows.Count)
{
DataRow row = reportData.Rows[printRowIndex];
cx = x;
for (int i = 0; i < reportData.Columns.Count; i++)
{
g.DrawString(row[i].ToString(), fontCell, brush, cx, y);
cx += colWidths[i];
}
y += 18;
printRowIndex++;
// Страница заполнена — перейти на следующую
if (y > e.MarginBounds.Bottom - 20)
{
e.HasMorePages = true;
return;
}
}
e.HasMorePages = false;
}
}
}