0
votes

I'm trying to print a receipt from a window Form using c#, it prints fine with only 1 row in the listview, but when more rows are added, they all print on the same line on the paper

How can I make it print it normally, one row below the other

here is the code I used

for (int i = 0; i < listView1.Items.Count; i++)
        {
            int ii = 1;
            ii++;

        graphics.DrawString("  " + listView1.Items[i].SubItems[0].Text + listView1.Items[i].SubItems[1].Text + listView1.Items[i].SubItems[2].Text + listView1.Items[i].SubItems[3].Text,  new Font("Arial Bold", 11),
                 new SolidBrush(Color.Black), startX, startY + Offset);
        }
        Offset = Offset + 20;
2
what is "ii" variable for? - NicoRiff
I thought using ii for subitems, but them it didn't work out alright so I removed it but forgot to remove this line, thanks for pointing it out - Joey Arnanzo

2 Answers

1
votes

It would be a much more better approach to iterate through your ListBox control using a foreach loop since you are going through all the items:

foreach(ListViewItem item in listView1.Items)
{
        graphics.DrawString("  " + item.SubItems[0].Text + item.SubItems[1].Text + item.SubItems[2].Text + item.SubItems[3].Text,  new Font("Arial Bold", 11),
                 new SolidBrush(Color.Black), startX, startY + Offset);

        Offset = Offset + 20;
}
0
votes

Put the line Offset = Offset + 20 within the for loop instead of after the closing bracket. Currently, your loop is printing everything, and after it finishes you are then incrementing Offset.

It may also be better to use Offset += 20 to make it more readable.

Also, as someone else has advised you use a foreach loop instead of a for loop, I disagree. A for loop in general requires less memory than a foreach loop and in this case, a for loop would be more suitable.

Please see here for information.

EDIT: Let me rescind my statement about for vs foreach in this particular case. Due to your loop accessing the array element several times during each iteration, in this example a foreach loop would be faster than a for loop.