In lstresult i put in the item name. in lstresult2 i put in the the numerical value for that item. i included a picture to show what i mean. I want to alphabetize lstResult but i want the value in lstResult2 to stay with the value. A better example is included in the picture.

Also how do you print lstResult and lstResult2 side by side like i have it in the picture i already put in the code for lstResult but i dont know how to get lstresult 2 to appear next to it. This is the code i have for that so far:

private int nextItem = 0;


         private void docPrint_PrintPage(object sender, PrintPageEventArgs e)
         {
             float linesPerPage = 0;
             float yPos = 0;
             float xPos = 0;
             int count = 0;
             float leftMargin = e.MarginBounds.Left;
             float topMargin = e.MarginBounds.Top;
             string line = null;
             m_objFont = new Font("Arial", 12);


             // Calculate the number of lines per page.
             linesPerPage = e.MarginBounds.Height /
             m_objFont.GetHeight(e.Graphics);

             // Print each line of the file.
             foreach (Control objControl in this.Controls)
             {
                 if (objControl.GetType().Name != "Button" && objControl.GetType().Name != "MenuStrip" && objControl.Name != "lblItemName" && objControl.Name != "lblItemValue" )
                 {
                     line = objControl.Text;

                     switch (objControl.Name)
                     {
                         case "lblSum":
                             e.Graphics.DrawRectangle(Pens.Black, lblSum.Location.X + leftMargin, lblSum.Location.Y + topMargin - 4, lblSum.Width, lblSum.Height);
                             m_objFont = objControl.Font;
                             break;

                         default:
                             m_objFont = objControl.Font;
                             m_objFont = new Font("Arial", 12);
                             break;

                     }
                     xPos = leftMargin + objControl.Location.X;
                     yPos = topMargin + objControl.Location.Y;
                     e.Graphics.DrawString(line, m_objFont, Brushes.Black, xPos, yPos);
                 }
             }
                             
             

                     while (count < linesPerPage && nextItem < lstResult.Items.Count)
                     {
                         m_objFont = new Font("Arial", 12, FontStyle.Underline);
                         yPos = topMargin + 195 + (count *
                         m_objFont.GetHeight(e.Graphics));
                         line = lstResult.Items[nextItem].ToString();
                         e.Graphics.DrawString(line, m_objFont, Brushes.Black,
                         leftMargin, yPos, new StringFormat());
                         count++;
                         nextItem++;
                     }
                     // If more lines exist, print another page.
                     if (nextItem < lstResult.Items.Count - 1)
                         e.HasMorePages = true;
                     else
                     {
                         e.HasMorePages = false;
                         nextItem = 0;
                     }
                 }
         
         
     

                         
                     
                 



             
             
         
         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);
         }

Any help would be appreciated to either or both of the questions. Thank You!

Dani AI

Generated

A cleaner, more robust way to keep each name paired with its numeric value is to model a row as a single object and bind both list controls to the same collection. That eliminates fragile manual reordering and makes sorting trivial. already has printing working; the remaining tasks are (1) keep name/value pairs together when sorting and (2) right‑align the numeric column on the printed page.

Bind both ListBoxes to one list of simple objects and sort that list. This keeps order consistent across both controls:

class ItemPair { public string Name { get; set; } public int Value { get; set; } }

var items = new BindingList<ItemPair> { /* populate */ };
listBoxNames.DataSource = items; listBoxNames.DisplayMember = "Name";
listBoxValues.DataSource = items; listBoxValues.DisplayMember = "Value";

// To alphabetize:
var sorted = items.OrderBy(p => p.Name).ToList();
items.Clear();
foreach (var p in sorted) items.Add(p);

For printing and right alignment of the numbers, prefer measuring or using a right-aligned StringFormat instead of space-padding (string.Format with fixed widths only reliably lines up columns when using a monospaced font). Example approach for the PrintPage loop:

var rightFmt = new StringFormat { Alignment = StringAlignment.Far };
float nameX = leftMargin;
float valueColumnWidth = 100f; // adjust to layout
var valueArea = new RectangleF(nameX, y, valueColumnWidth, lineHeight);
e.Graphics.DrawString(item.Name, font, Brushes.Black, nameX, y);
e.Graphics.DrawString(item.Value.ToString(), font, Brushes.Black, valueArea, rightFmt);

A note on sorting algorithms: the swap-based routine posted by works for small lists but is O(n^2); for larger collections prefer List<T>.Sort or LINQ OrderBy as shown. If a true two-column visual is required, consider a ListView (Details) or DataGridView — they keep rows together and simplify printing/layout.

Recommended Answers

All 10 Replies

Ok i was able to get it to print both list boxes. Now my quesiton is how do i Left Align the numbers on the printed page like i have in the program?

Also how do i sort both listboxes together?

*right align

Use string.Format method.

for(int i=9;i<=12;i++)
     string str=string.Format("{0,-20}{1,20}", i, i*i);

im sorry but i dont understand what you mean.

i want to sort it alphabetically but i want to keep the value with the name. Like the example in the picture. I have Galaxolide in lstResult and the value 250 that goes with Galaxolide in lstResult2. If this cant be done, how do i fix the code to combine it into a single listbox with two columns. I would prefer the two listboxes like i have now but if it cant be done it can be put in a single listbox with two columns also.

thanks for the reply but i tried that method already. it wasnt really what i was looking for,

Could you please elaborate on what it really is you are looking for?

>I want to alphabetize lstResult but i want the value in lstResult2 to stay with the value.

object  tmp = "";
            for (int i = 0; i < listBox1.Items.Count - 1; i++)
            {
                for (int j = i + 1; j < listBox1.Items.Count; j++)
                {
                    if( string.Compare(listBox1.Items[i].ToString(), listBox1.Items[j].ToString())>0)
                    {
                        tmp = listBox1.Items[i];
                        listBox1.Items[i] = listBox1.Items[j];
                        listBox1.Items[j] = tmp;

                        tmp = listBox2.Items[i];
                        listBox2.Items[i] = listBox2.Items[j];
                        listBox2.Items[j] = tmp;
                    }

                }
            }
commented: Bubblesort is an option of course +8

Thanks So Much!!!

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.