When print preview button is clicked, it displays all the data that is going to be print. I only want to select the row that I want, and let it print. And I want each field to have each own line, because also since I have too many fields, my mcCentre and nFirstName cannot display on the print preview.
(etc on the print preview)
appointmentID : 2
pDate : 5/3/2014
aTime : 11.30am
aStatus : waiting
...(continue until the last field)
My AppointmentForm
AppointmentPrintPreview once print preview button is clicked
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace GRP_02_03_SACP
{
public partial class appointment : Form
{
// Data Table to store employee data
DataTable Appointment = new DataTable();
// Keeps track of which row in Gridview
// is selected
DataGridViewRow currentRow = null;
SqlDataAdapter AppointmentAdapter;
public appointment()
{
InitializeComponent();
}
private void appointment_Load(object sender, EventArgs e)
{
LoadMedicalCentreRecords();
}
private void LoadMedicalCentreRecords()
{
//retrieve connection information info from App.config
string strConnectionString = ConfigurationManager.ConnectionStrings["sacpConnection"].ConnectionString;
//STEP 1: Create connection
SqlConnection myConnect = new SqlConnection(strConnectionString);
//STEP 2: Create command
string strCommandText = "SELECT appointmentID, aDate, aTime, aStatus, aContact, aHeight, aWeight, p.pFirstName , m.mcCentre , n.nFirstName FROM APPOINTMENT AS a LEFT OUTER JOIN Nurse AS n ON a.nurseID = n.NurseID Left outer join Patient as p on a.patientid = p.patientId left outer join medicalcentre as m on a.mcID = m.mcid";
AppointmentAdapter = new SqlDataAdapter(strCommandText, myConnect);
//command builder generates Select, update, delete and insert SQL
// statements for MedicalCentreAdapter
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(AppointmentAdapter);
// Empty Employee Table first
Appointment.Clear();
// Fill Employee Table with data retrieved by data adapter
// using SELECT statement
AppointmentAdapter.Fill(Appointment);
// if there are records, bind to Grid view & display
if (Appointment.Rows.Count > 0)
grdApp.DataSource = Appointment;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int modifiedRows = 0;
// Get changes
DataTable UpdatedTable = Appointment.GetChanges();
if (UpdatedTable != null)
{
// there are changes
// Write modified data to database
modifiedRows = AppointmentAdapter.Update(UpdatedTable);
// accept changes
Appointment.AcceptChanges();
}
else
MessageBox.Show("there are no changes to update");
if (modifiedRows > 0)
{
MessageBox.Show("There are " + modifiedRows + " records updated");
LoadMedicalCentreRecords();
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
if (printDialog1.ShowDialog() == DialogResult.OK) // this displays the dialog box and performs actions dependant on which option chosen.
{
printDocument1.Print();
}
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int columnPosition = 0;
int rowPosition = 25;
// run function to draw headers
DrawHeader(new Font(this.Font, FontStyle.Bold), e.Graphics, ref columnPosition, ref rowPosition); // runs the DrawHeader function
rowPosition += 35; // sets the distance below the header text and the next black line (ruler)
// run function to draw each row
DrawGridBody(e.Graphics, ref columnPosition, ref rowPosition);
}
// DrawHeader will draw the column title, move over, draw the next column title, move over, and continue.
private int DrawHeader(Font boldFont, Graphics g, ref int columnPosition, ref int rowPosition)
{
foreach (DataGridViewColumn dc in grdApp.Columns)
{
//MessageBox.Show("dc = " + dc);
g.DrawString(dc.HeaderText, boldFont, Brushes.Black, (float)columnPosition, (float)rowPosition);
columnPosition += dc.Width + 5; // adds to colPos. value the width value of the column + 5.
}
return columnPosition;
}
/* DrawGridBody will loop though each row and draw it on the screen. It starts by drawing a solid line on the screen,
* then it moves down a row and draws the data from the first grid column, then it moves over, then draws the data from the next column,
* moves over, draws the data from the next column, and continus this pattern. When the entire row is drawn it starts over and draws
* a solid line then the row data, then the next solid line and then row data, etc.
*/
private void DrawGridBody(Graphics g, ref int columnPosition, ref int rowPosition)
{
// loop through each row and draw the data to the graphics surface.
foreach (DataRow dr in ((DataTable)grdApp.DataSource).Rows)
{
columnPosition = 0;
// draw a line to separate the rows
g.DrawLine(Pens.Black, new Point(0, rowPosition), new Point(this.Width, rowPosition));
// loop through each column in the row, and draw the individual data item
foreach (DataGridViewColumn dc in grdApp.Columns)
{
// draw string in the column
string text = dr[dc.DataPropertyName].ToString();
g.DrawString(text, this.Font, Brushes.Black, (float)columnPosition, (float)rowPosition + 10f); // the last number (10f) sets the space between the black line (ruler) and the text below it.
// go to the next column position
columnPosition += dc.Width + 5;
}
// go to the next row position
rowPosition = rowPosition + 60; // this sets the space between the row text and the black line below it (ruler).
}
}
private void btnPrintPreview_Click(object sender, EventArgs e)
{
try
{
// PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog(); // instantiate new print preview dialog
printPreviewDialog1.Document = this.printDocument1;
if (printPreviewDialog1.ShowDialog() == DialogResult.OK) // Show the print preview dialog, uses printPage event to draw preview screen
{
printDocument1.Print();
}
}
catch (Exception exp)
{
System.Console.WriteLine(exp.Message.ToString());
}
}
}
}
Print Grid view all Data Show with paging in PrintPrivew Try This Perfect Working..
private void printDocumentRpt_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
try
{
int iLeftMargin = e.MarginBounds.Left;
int iTopMargin = e.MarginBounds.Top;
bool bMorePagesToPrint = false;
int iTmpWidth = 0;
if (bFirstPage)
{
foreach (DataGridViewColumn GridCol in GvShowData.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) + 22;
arrColumnLefts.Add(iLeftMargin);
arrColumnWidths.Add(iTmpWidth);
iLeftMargin += iTmpWidth;
}
}
while (iRow <= GvShowData.Rows.Count - 1)
{
DataGridViewRow GridRow = GvShowData.Rows[iRow];
iCellHeight = GridRow.Height + 15;
int iCount = 0;
double totalcount = Convert.ToDouble(iRow) % Convert.ToDouble(10);
if (totalcount == 0 && iRow != 0 && totalrecord == 0)
{
bNewPage = true;
bFirstPage = false;
bMorePagesToPrint = true;
totalrecord = 1;
break;
}
else
{
if (bNewPage)
{
e.Graphics.DrawString("Gridview Header", new System.Drawing.Font(GvShowData.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
e.Graphics.MeasureString("Gridview Header", new System.Drawing.Font(GvShowData.Font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
String strDate = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
e.Graphics.DrawString(strDate, new System.Drawing.Font(GvShowData.Font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(strDate, new System.Drawing.Font(GvShowData.Font,
FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
e.Graphics.MeasureString("Gridview Header", new System.Drawing.Font(new System.Drawing.Font(GvShowData.Font,
FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);
iTopMargin = e.MarginBounds.Top;
foreach (DataGridViewColumn GridCol in GvShowData.Columns)
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
new System.Drawing.Rectangle((int)arrColumnLefts[iCount], iTopMargin,
(int)arrColumnWidths[iCount], iHeaderHeight));
e.Graphics.DrawRectangle(Pens.Black,
new System.Drawing.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;
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);
}
e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)arrColumnLefts[iCount],
iTopMargin, (int)arrColumnWidths[iCount], iCellHeight));
iCount++;
}
}
iRow++;
iTopMargin += iCellHeight;
totalrecord = 0;
}
if (bMorePagesToPrint)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void printDocumentRpt_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
try
{
strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Near;
strFormat.LineAlignment = StringAlignment.Center;
strFormat.Trimming = StringTrimming.EllipsisCharacter;
arrColumnLefts.Clear();
arrColumnWidths.Clear();
iCellHeight = 0;
iRow = 0;
bFirstPage = true;
bNewPage = true;
iTotalWidth = 0;
foreach (DataGridViewColumn dgvGridCol in GvShowData.Columns)
{
iTotalWidth += dgvGridCol.Width;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
printDocumentRpt.DocumentName = "Test Page Print";
printPreviewDialogRpt.Document = printDocumentRpt;
printPreviewDialogRpt.ShowDialog();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.