Printing
a document in Windows Forms
In Visual studio, there is a built-in controller which makes
the printing job much easy. I’m quoting a sample WinForm application to print
data dynamically.
First Create a new Windows Form application. Create a form similar
to this
The ids of the text boxes I’ve created are Item1, Price1, Item2, Price2 respectively.
You can enter the contents in the textboxes. Also include
these codes:
private void Form1_Load(object
sender, EventArgs e)
{
Price_TextChanged(sender, e);
//To show the total onload. I just
hardcoded the test valuses in those text boxes.
}
//Fires whern the
print button is clicked
private void button1_Click(object
sender, EventArgs e)
{
printDocument1.Print();
}
//Fires when its
starting the print. For printing we have to fill the print document with
a Graphics canvas. This is inhirited from the System.Drawing class
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs
e)
{
e.Graphics.DrawString(ShopName.Text, new Font(FontFamily.GenericSansSerif, 15, FontStyle.Bold), Brushes.Blue,
75, 30);
e.Graphics.DrawString(Item1.Text,
DefaultFont, Brushes.Black, 50, 80);
e.Graphics.DrawString(Price1.Text,
DefaultFont, Brushes.Black, 150, 80);
e.Graphics.DrawString(Item2.Text,
DefaultFont, Brushes.Black, 50, 100);
e.Graphics.DrawString(Price2.Text,
DefaultFont, Brushes.Black, 150, 100);
e.Graphics.DrawString("Total", new
Font(FontFamily.GenericSansSerif,
15, FontStyle.Bold), Brushes.Red, 50, 130);
e.Graphics.DrawString(Total.Text, new Font(FontFamily.GenericSansSerif, 15, FontStyle.Bold), Brushes.Red,
150, 130);
}
//This is for updating the total amount when the values in the textbox changed and form onload
private void Price_TextChanged(object
sender, EventArgs e)
{
Total.Text = (Convert.ToInt32(Price1.Text ?? "0") + Convert.ToInt32(Price2.Text
?? "0")).ToString();
}
Thank you very much.I was looking for a simple example. You are great! Thanks again. Looking forwad for more from you.
ReplyDelete-Steve