AutoSize and the ComboBox

I had a need tonight to dynamically size the DropDown of a ComboBox control on a WinForms tool I was writing, and while I was hoping to find an AutoSize property on the ComboBox as it exists on the Label control, I was out of luck.

My ComboBox only needs to be sized after initial population at run time, so performance wasn't a primary concern. There may be a better way of doing this but in case anyone else out there was in the same spot I was in tonight here is my hack.

       void SetWidth(ComboBox c)
            int maxSize = 0;
            System.Drawing.Graphics g = CreateGraphics();

        for (int i = 0; i < c.Items.Count; i++)
            c.SelectedIndex = i;
            SizeF size = g.MeasureString(c.Text, c.Font);
            if (maxSize < (int)size.Width)
                maxSize = (int)size.Width;

        c.DropDownWidth = c.Width;
        if (c.DropDownWidth < maxSize)
            c.DropDownWidth = maxSize;

        c.SelectedIndex = -1;

Update: In an IM session tonight with Ben Harrell, I asked him to review this and tell me if this was the correct way of going about this task in 2.0 or was I missing something simple. He pointed me to this MSDN article about building a better ComboBox which details essentially the same thing, however, it did highlight a couple of bugs in the above code that I forgot about -- disposing of my Graphics handle and checking for the bounds of the screen.

Tags: c#, winforms, combobox, autosize, controls, development, code, sample