在c#

时间:2017-03-06 01:00:42

标签: c#

我正在尝试从列表框中获取所有值,然后将值打印为收据,我尝试使用foreach循环获取列表框中的所有值,但在打印预览中,它只显示1个值。

这是我的代码:

foreach (object items in listBox1.Items)
        {
            Ticket tkt = new Ticket();
            tkt.orders = items.ToString();
            tkt.print();
        }

这是来自Ticket Class的代码:

PrintDocument pdoc = null;
       String Name, Order,
       public String orders
    {
        //set the person name
        set { this.Order = value; }
        //get the person name 
        get { return this.Order; }
    }public Ticket(String Orders)
    {

        this.orders = Orders;

    }
public void print()
    {
        PrintDialog pd = new PrintDialog();
        pdoc = new PrintDocument();
        PrinterSettings ps = new PrinterSettings();
        Font font = new Font("Courier New", 15);


        PaperSize psize = new PaperSize("Custom", 100, 200);
        //ps.DefaultPageSettings.PaperSize = psize;



        pd.Document = pdoc;
        pd.Document.DefaultPageSettings.PaperSize = psize;
        //pdoc.DefaultPageSettings.PaperSize.Height =320;
        pdoc.DefaultPageSettings.PaperSize.Height = 820;

        pdoc.DefaultPageSettings.PaperSize.Width = 520;

        pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage);

        DialogResult result = pd.ShowDialog();
        if (result == DialogResult.OK)
        {
            PrintPreviewDialog pp = new PrintPreviewDialog();
            pp.Document = pdoc;
            result = pp.ShowDialog();
            if (result == DialogResult.OK)
            {
                pdoc.Print();
            }
        }

    }
       void pdoc_PrintPage(object sender, PrintPageEventArgs e)
    {
        Graphics graphics = e.Graphics;
        Font font = new Font("Courier New", 10);
        float fontHeight = font.GetHeight();
        int startX = 50;
        int startY = 55;
        int Offset = 40;
          Offset = Offset + 20;
        String Orders = this.orders;
        graphics.DrawString("Orders :" + orders, new Font("Courier New", 10), new SolidBrush(Color.Black), startX, startY + Offset);
}

提前致谢

1 个答案:

答案 0 :(得分:1)

这永远不会做你想要的。

该代码基本上是说

for each item in the listbox
   create a new ticket
   set the string property to item[x].Value.ToString
   print it as it is
   x++
next

你需要像

这样的东西
Ticket tkt = new Ticket();    
foreach (object ticItems in listBox1.Items)
            {
                var order = new order{item = ticItems.ToString}
                tkt.orders.Add(order)
            }
 tkt.print();

这:

  • 创建新故障单
  • 将每个项目添加到其Orders属性中 应该是(List<string>
  • 然后全部加载打印