Hi! im sorry i keep asking so many questions but i really want to learn. I want to know how to get my program to print the items that i have in my two listboxes titled lstResult and lstResult2. This is what i have so far:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;

namespace Perfume_Formula_Typing_Software
{
     public partial class Form1 : Form
    {
        List<double> values;
        public Form1()
        {
            InitializeComponent();
        }
       
            
        private void Form1_Load(object sender, EventArgs e)
        {
            values = new List<double>();
        }
        void ShowValues()
        {
            lstResult2.Items.Clear();
            for (int i = 0; i < values.Count; i++)
                lstResult2.Items.Add(values[i]);
            lblSum.Text = values.Count.ToString();
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {

            double value = 0.00;
            double sum = 0.00;


            if (txtItemName.Text == "" || txtItemValue.Text == "")
            {
                MessageBox.Show("Please Enter A Value In All Fields.", "Missing Information");
                return;
            }
            else
            {
                lstResult.Items.Add(txtItemName.Text);
                txtItemName.Text = "";

                try
                {
                    value = double.Parse(txtItemValue.Text);
                    values.Add(value);
                    ShowValues();
                    txtItemValue.Text = "";
                    txtItemName.Focus();
                }
                catch (FormatException)
                {
                    
                }
                for (int i = 0; i < values.Count; i++)
                    sum += values[i];
                lblSum.Text = sum.ToString("F");
            }
          }

        private void mnuFileNew_Click(object sender, EventArgs e)
        {
            txtFormulaName.Text = "";
            txtFormulaNumber.Text = "";
            txtItemName.Text = "";
            comboBox1.Text = "";
            lstResult.Items.Clear();
            lstResult2.Items.Clear();
            
        }

        private void mnuFileOpen_Click(object sender, EventArgs e)
        {
            dlgOpen.InitialDirectory = @"C:\";

            if (dlgOpen.ShowDialog() == DialogResult.OK)
            {
                FileStream fileAndorHunsFormulaWorksheet = new FileStream(this.dlgOpen.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                BinaryReader bnrAndorHunsFormulaWorksheet = new BinaryReader(fileAndorHunsFormulaWorksheet);
                lblSum.Text = bnrAndorHunsFormulaWorksheet.ReadString();
                txtFormulaName.Text = bnrAndorHunsFormulaWorksheet.ReadString();
                string item = bnrAndorHunsFormulaWorksheet.ReadString();
                int index = comboBox1.FindString(item);
                if ((index != -1 & !string.IsNullOrEmpty(item)))
                {
                    comboBox1.SelectedIndex = index;
                }
                txtFormulaNumber.Text = bnrAndorHunsFormulaWorksheet.ReadString();
                
                
                int number = lstResult2.Items.Count;
                lstResult2.Items.Clear();
                lstResult.Items.Clear();
                bool switchAction = false;
                while (bnrAndorHunsFormulaWorksheet.PeekChar() != -1)
                {

                    string str = bnrAndorHunsFormulaWorksheet.ReadString();
                    if (str == "@") 
                    { 
                        switchAction = true; 
                        continue;
                    } 
                    if (switchAction) 
                        lstResult.Items.Add(str);
                    else 
                        lstResult2.Items.Add(str);
                    
                }
                bnrAndorHunsFormulaWorksheet.Close();
                fileAndorHunsFormulaWorksheet.Close();
            }

        }

        private void mnuFileSave_Click(object sender, EventArgs e)
        {
            if (dlgSave.ShowDialog() == DialogResult.OK)
            {
               
                FileStream fileAndorHunsFormulaWorksheet = new FileStream(dlgSave.FileName, FileMode.Create, FileAccess.Write, FileShare.Write);
                BinaryWriter bnrAndorHunsFormulaWorksheet = new BinaryWriter(fileAndorHunsFormulaWorksheet);
                bnrAndorHunsFormulaWorksheet.Write(lblSum.Text);
                bnrAndorHunsFormulaWorksheet.Write(txtFormulaName.Text);
                bnrAndorHunsFormulaWorksheet.Write(comboBox1.Text);
                bnrAndorHunsFormulaWorksheet.Write(txtFormulaNumber.Text);
                foreach (object ls in lstResult2.Items)
                {
                    bnrAndorHunsFormulaWorksheet.Write(ls.ToString());
                }
                bnrAndorHunsFormulaWorksheet.Write("@"); // Marker
                foreach (object ls in lstResult.Items)
                {                   
                    bnrAndorHunsFormulaWorksheet.Write(ls.ToString());                
                }
                
                bnrAndorHunsFormulaWorksheet.Close();
                fileAndorHunsFormulaWorksheet.Close();
            }
                
        }

        private void btnRemoveValue_Click(object sender, EventArgs e)
        {
            
            lstResult2.Items.Remove(lstResult2.SelectedItem);
            

            

            
        }

        private void btnRemoveItem_Click(object sender, EventArgs e)
        {
            lstResult.Items.Remove(lstResult.SelectedItem);
        }

         private void docPrint_PrintPage(object sender, PrintPageEventArgs e)
         {
             float fltYPosition;
             float fltXPosition;
             
             float fltLeftMargin = e.MarginBounds.Left;
            
             float fltTopMargin = e.MarginBounds.Top;
             string strLine = "";

             foreach (Control objControl in this.Controls)
             {
                 if (objControl.GetType().Name != "Button")
                 {
                     strLine = objControl.Text;
                     
                     switch (objControl.Name)
                     {
                         case "lblSum":
                             e.Graphics.DrawRectangle(Pens.Black, lblSum.Location.X + fltLeftMargin, lblSum.Location.X + fltTopMargin - 4, lblSum.Width, lblSum.Height);
                             m_objFont = objControl.Font;
                             break;

                         default:
                             m_objFont = objControl.Font;
                             break;
                     }
                     fltXPosition = fltLeftMargin + objControl.Location.X;
                     fltYPosition = fltTopMargin + objControl.Location.Y;

                     e.Graphics.DrawString(strLine, m_objFont, Brushes.Black, fltXPosition, fltYPosition);
                 }



             }
             e.Graphics.DrawRectangle(Pens.Black, fltLeftMargin, fltTopMargin, this.Width, this.Height - 60);
             e.HasMorePages = false;
         }
         private void mnuFilePrint_Click(object sender, EventArgs e)
         {
             PrintDocument docPrint = new PrintDocument();
             docPrint.PrintPage += new PrintPageEventHandler(docPrint_PrintPage);

             if (PrinterSettings.InstalledPrinters.Count == 0)
             {
                 ErrorMessage();
                 return;
             }
             docPrint.Print();
         }

         private void mnuFilePrintPreview_Click(object sender, EventArgs e)
         {
             PrintDocument docPrint = new PrintDocument();

             docPrint.PrintPage += new PrintPageEventHandler(docPrint_PrintPage);
             if (PrinterSettings.InstalledPrinters.Count == 0)
             {
                 ErrorMessage();
                 return;
             }
             objPreview.Document = docPrint;
             objPreview.ShowDialog();

         }
         void ErrorMessage()
         {
             MessageBox.Show("No printers istalled. You must" + "have a printer installed to preview or print" + "the document.", "Print Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
        

       

       

       
    }
}

Dani AI

Generated

Notes for :

Printing the ListBox items directly is simpler and more reliable than iterating every Control on the form. Use the PrintPage handler to walk the ListBox.Items collection, measure line height from the Graphics object, and implement simple pagination. Avoid using control.Location values for print coordinates — use e.MarginBounds so output respects printer margins.

Example PrintPage handler that prints the two listboxes side-by-side, tracking progress across pages:

// class-level fields
int _leftIndex = 0;
int _rightIndex = 0;

private void doc_PrintPage(object sender, PrintPageEventArgs e)
{
    using (Font printFont = new Font("Arial", 10))
    {
        float lineHeight = printFont.GetHeight(e.Graphics) + 2f;
        float leftX = e.MarginBounds.Left;
        float rightX = e.MarginBounds.Left + e.MarginBounds.Width / 2;
        float y = e.MarginBounds.Top;

        while (y + lineHeight <= e.MarginBounds.Bottom)
        {
            bool drew = false;
            if (_leftIndex < lstResult.Items.Count)
            {
                string leftText = lstResult.Items[_leftIndex++].ToString();
                e.Graphics.DrawString(leftText, printFont, Brushes.Black, leftX, y);
                drew = true;
            }
            if (_rightIndex < lstResult2.Items.Count)
            {
                string rightText = lstResult2.Items[_rightIndex++].ToString();
                e.Graphics.DrawString(rightText, printFont, Brushes.Black, rightX, y);
                drew = true;
            }
            if (!drew) break;
            y += lineHeight;
        }

        e.HasMorePages = (_leftIndex < lstResult.Items.Count) || (_rightIndex < lstResult2.Items.Count);
        if (!e.HasMorePages) { _leftIndex = _rightIndex = 0; }
    }
}

Troubleshooting notes:

  • Reset the indices in PrintDocument.BeginPrint if the same PrintDocument instance is reused.
  • Use PrintPreviewDialog for layout checks before sending to a physical printer.
  • For long item text consider MeasureString and DrawString with a layout rectangle (wrap) or trim the text.
  • Check PrinterSettings.InstalledPrinters before printing and handle exceptions from the printing subsystem.

This approach keeps layout predictable, supports multiple pages, and prints exact ListBox contents rather than form controls.

any help would be greatly appreciated

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.