Click here to Skip to main content
15,887,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello
i want to print Values from database using print dialog in c#.
i want to print print 1 value at a page but it is not working. It only prints 2 pages and then Prints all values at first page. Please tell me what should i do with this.
My code is

At Print Page Event
PaperSize paperSize = new PaperSize("papersize", 200, 100); //page size 2X1 inches approx
int totalnumber2 = 0;

public void PrintDocumentOnPrintPage(object sender, PrintPageEventArgs e)
{
SqlCommand cm;
DataTable dt = new DataTable();
try
{
DBConnection DB = new DBConnection();
DB.cnTransact.Open();
string sql = "select * from tbl_items";
cm = new SqlCommand(sql, DB.cnTransact);
SqlDataAdapter people = new SqlDataAdapter(cm);
people.Fill(dt);
int xValue = 25;
int yValue = 30;
int yValue2 = 65;
float pageheight = e.MarginBounds.Height;
int x = 0;
foreach (DataRow dr in dt.Rows)
{
string itemx = dr["item_id"].ToString().PadLeft(6,'0'); ;
string item2 = "*"+itemx+"*";
string item3 = "*UMS" + itemx + "*";
e.Graphics.DrawString(item2, new Font("Free 3 of 9", 30, FontStyle.Regular), Brushes.Black, xValue, yValue);
e.Graphics.DrawString(item3, new Font("Courier New", 14, FontStyle.Regular), Brushes.Black, xValue, yValue2);
if (totalnumber2 < dt.Rows.Count)
{
e.HasMorePages =true;
}
else {
e.HasMorePages = false;
}
totalnumber2++;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

At Button Click Event

private void btn1_Click(object sender, EventArgs e)
{
totalnumber2 = 0;
PrintDialog dialog = new PrintDialog();
PrintDocument printDocument = new PrintDocument();
dialog.Document = printDocument;
printDocument.DefaultPageSettings.PaperSize = paperSize;
dialog.ShowDialog();
printDocument.PrintPage += PrintDocumentOnPrintPage;
printDocument.DocumentName = "Barcodes";
printDocument.Print();
}

Please tell me where i am doing mistakes and help me in solving this.
Thanks
Posted

1 solution

The PrintPage method is called once for each page printed until e.HasMorPages is set to false - which means your whole data retrieval routine is being executed on each page....

You need to get your data outside this method, print only the records that fit on the current page, and update the current record pointer each time a record is printed.

Check out this: An absolute beginner's guide to printing in .NET[^] (it also applies to C#)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900