Print from a listbox using C#

Well, I decided to get this blog started by posting a C# tutorial, and try to lead you how to print the content of a listbox. If you have some data, and you’d like to print it without using all that report stuff, it’s an easy and safe way to go.

So let’s code…

I’m using Visual Studio 2010, but you should use the one you’re used to, I’m almost sure it’s going to work well in different versions too. So, first of all, create a new Project, a New Form Application one.

After that, fill your form with a listbox and one button, it should look like that.pic1

We must have data to print, so go to onLoad() method and fill your listbox.

1 private void Form1_Load(object sender, EventArgs e) 2 { 3 for (int i = 0; i < 10; i++) 4 { 5 listBox1.Items.Add("test number " + i); 6 } 7 }

So, we already have 10 lines to print and, what now? It’s time to actually start using printing tools. Before you start coding, add to your project this 2 components (both are presented at tab “Printing”):

– PrintDialog
– PrintDocument

Right, after that, you should add one property to the second component, go to this method (you can find it in your Form1.Designer.cs file:

1 private void InitializeComponent()

And you should add this line code:

1 // 2  // printDocument1 3  // 4  this.printDocument1.PrintPage += new System.Drawing.Printing. 5 PrintPageEventHandler(this.printDocument1_PrintPage);

Note that the single argument you should pass is a method we’ll set up later, so it doesn’t matter if VS complains about it.

Go back to your Form1.cs and add 3 things:

1) Necessary to print

1 using System.IO; 2  using System.Collections;

2) Our variable we’re going to use to print the whole listbox content.

1 private StringReader myReader;

Well, now just copy and past the following method, it’s already commented, so if you have doubts about its own behavior, let me know that.

1 protected void printDocument1_PrintPage(object sender, 2 System.Drawing.Printing.PrintPageEventArgs ev) 3 { 4 float linesPerPage = 0; 5 float yPosition = 0; 6 int count = 0; 7 float leftMargin = ev.MarginBounds.Left; 8 float topMargin = ev.MarginBounds.Top; 9 string line = null; 10 Font printFont = this.listBox1.Font; 11 SolidBrush myBrush = new SolidBrush(Color.Black); 12 13 // Work out the number of lines per page, using the MarginBounds. 14   linesPerPage = 15 ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics); 16 17 // Iterate over the string using the StringReader, printing each line. 18   while (count < linesPerPage && ((line = myReader.ReadLine()) != null)) 19 { 20 // calculate the next line position based on 21 // the height of the font according to the printing device 22   yPosition = topMargin + (count * printFont.GetHeight(ev.Graphics)); 23 24 // draw the next line in the rich edit control 25   26 ev.Graphics.DrawString(line, printFont, 27 myBrush, leftMargin, 28 yPosition, new StringFormat()); 29 count++; 30 } 31 32 // If there are more lines, print another page. 33 if (line != null) 34 ev.HasMorePages = true; 35 else 36 ev.HasMorePages = false; 37 38 myBrush.Dispose(); 39 }

Well, we have almost everything set up to print, except for the button1 code. Double click on it and you have a few last lines to code.

1 private void button1_Click(object sender, EventArgs e) 2 { 3 printDialog1.Document = printDocument1; 4 string strText = ""; 5 foreach (object x in listBox1.Items) 6 { 7 strText = strText + x.ToString() + "\n"; 8 } 9 10 myReader = new StringReader(strText); 11 if (printDialog1.ShowDialog() == DialogResult.OK) 12 { 13 this.printDocument1.Print(); 14 } 15 }

So, it’s basically copying the content into a string adding the “\n” and, at the end, calling the printer.

Let’s test our application and…

Hooray! Open-mouthed smile

Well, that’s it! It’s a really easy way to print data from a listbox, if you have any doubts or might want to add any information, use the comment area below.

Thank you!

Advertisements

41 comments

  1. I’ve been trawling the web and this is the best, easiest to understand tute out there on the subject.
    Thanks

    1. Hello Renee,

      Thanks for the feedback, it is important 🙂

      Well, what exactly do you mean by ‘smaller chars’? Is it the font size? You can set this up in your listbox properties.
      Hope it helps.

      Regards, Felipe.

  2. Yes! I mean the font size. But in properties i will have font size 14 and when I print I will have font size 8. You undersand me? Im sorry for spelling mistakes.

    1. Oh, I see.
      That’s weird, when I did this tutorial it worked for me.
      You said that when you have font size 14 in your listbox, it seems to have font size 8 when you print it.
      Is it linear? I mean, when you setup font size to 28 in your listbox, do you have 16 when you print it? Can you check that please?
      Sorry if it was too complicated.

      Regards, Felipe

  3. In my lisbox properites I have font size on 16. When i printing from listbox I also have the font size 16.
    But by printing I want have the font size 8. (only by printing)
    Understand?

    Thank you! Best Regards Rene!

    1. Oh, now I get it!
      You still wanna keep the size 16 in listbox but print it with 8. I guess it’s not possible.

      One alternative is, before print, set the listbox font size to 8, print and then get it back to 16. I know it’s not a sweet alternativa, but it should work, doesn’t it?

      Regards, Felipe.

  4. hey after clickin on d print button d xps doc is nt gettin saved ….wat 2 do…?? n also cn i put d logo of the company in the list box so dat it appear on the bill pls rly asap…..

    1. Hello,

      Well, I recommend for you to use RichTextBox, you know?
      You can put your logo there, save the file and call it to be printed using the method in this “Print from a listbox using C#” tutorial.
      I’ve done stuff like that and it worked pretty well.

      If you have any kinda trouble with that let me know and I try to help you.
      Regards,
      Felipe

    1. Hello Angela,

      In fact this method does not deppend on the listbox itselt, all you need to do is build your string correctly using data from your multilistbox and send it to printer.

      Regards,
      Felipe

  5. this didn’t work for me. on your line “while(count<linsPerPage && ((line=myReader.ReadLine())null))" i am getting the following errors:

    – Operator '&&' cannot be applied to operands of type 'bool' and 'string'
    – Only assignment, call, increment, decrment, and new object expressions can be used as a statement

  6. Hi,
    Thanks for this great tutorial it’s helped me out a lot.
    My list box contains many items that are very short in name. I was wondering if there is a way to print out in columns as to not waste paper.

    1. Hello Akatsuki,

      In fact I haven’t thought about printing in columns but I’m sure it has to be a way to do that.
      I’ll search for a solution and if I find something I email you.

      Regards,
      Felipe

  7. Hello Felipe,

    Thank you for this comprehensible tutorial! I look forward to seeing what other great stuff you have in the blog!

    Thanks again!

    Best,
    Bryan

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s