tags:

views:

37

answers:

2

I have a Winforms dropdown. The drop down displays a string that is in the form of...

<Description 30chars> Weight:<weight 6chars> Thickness:<thickness 6chars>

I need the strings to line up so Weight always starts at the same spot. So when there is a list of them everything lines up nicely.

My current solution was to use a monospaced font and create a display string that pads each part with spaces to get everything to line up. However the font looks different than the rest of the application and the beta testers did not approve. Is there a way to get text to line up without using a mono spaced font? This way I can use the same font that is used for the rest of the application.

Thank you

+1  A: 

Take a look at the DrawItem event for the ComboBox. There you can do any kind of formatting. Make sure you set the DrawMode to OwnerDrawXXXX.

 private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            ComboBox cb = (ComboBox)sender;
            int index = e.Index;
            Graphics g = e.Graphics;

            DataItem item = (DataItem)cb.Items[index];

            g.DrawString(item.Name, new Font("Arial", 8), new SolidBrush(Color.Blue), 0, e.Bounds.Y);
            g.DrawString(item.Age.ToString(), new Font("Arial", 8), new SolidBrush(Color.Blue), 100, e.Bounds.Y);
        }

        public class DataItem
        {
            public string Name;
            public int Age;

            public override string ToString()
            {
                return string.Format("{0} {1}", Name, Age);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add(new DataItem { Name = "Apple", Age = 10 });
            comboBox1.Items.Add(new DataItem { Name = "Berry", Age = 20 });
            comboBox1.Items.Add(new DataItem { Name = "Cherry", Age = 30 });
        }
Dan Vallejo
needs the e.DrawBackground() and e.DrawFocusRectangle() but otherwise a good example. Thanks.
Tony
You get the answer mark over Hans only because you were first. Both answers are correct.
Tony
+1  A: 

This looks like a very webby kind of question, I'll assume you are talking about ComboBox. Yes, there's something you can do with its DrawMode property. When you set it to OwnerDrawFixed then you can implement a DrawItem event handler and draw the dropdown items just the way you want them. There's a very good example in the MSDN Library topic for that event.

You'll need to do extra work to also get it displayed properly in the text box portion of the combo box. Shouldn't be a problem, you don't need columns for that. Perhaps you can separate the items with a distinctive character, one that you can also use in your DrawItem event to find the column text back.

Hans Passant
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.drawitem.aspx is the MSDN link
Tony