topgun_ivard
topgun_ivard

Reputation: 8594

WinForms ComboBox problem

In a Windows Form Application, I have a ComboBox1 which gets initialized in InitializeComponent() function. I add the values into it in a different function.

snippet:

    public form1()
    {
        InitializeComponent();
        addDataToDropDowns();
    }

The problem I have is that, the rows loaded into the ComboBox1 have many characters(/length) and are not to be seen completely width wise.

Is it possible to have a horizontal scrollbar built into the ComboBox1 so that I can see the hidden part of the row too...??

Any ideas/inputs will be appreciated!

Thanks, Ivar

Upvotes: 0

Views: 1659

Answers (3)

Peet Brits
Peet Brits

Reputation: 3265

Combining the links in Caladain's answer, here is the code. It works for both strings and data bound objects. The method cbSample_DropDown() is linked to the DropDown event of the ComboBox.

private void AdjustWidthComboBox(ComboBox comboBox)
{
    int width = comboBox.DropDownWidth;
    using (Graphics g = comboBox.CreateGraphics())
    {
        Font font = comboBox.Font;
        int vertScrollBarWidth =
            (comboBox.Items.Count > comboBox.MaxDropDownItems)
            ? SystemInformation.VerticalScrollBarWidth : 0;

        foreach (object item in comboBox.Items)
        {
            string valueToMeasure = comboBox.GetItemText(item);
            int newWidth = (int)g.MeasureString(valueToMeasure, font).Width + vertScrollBarWidth;
            if (width < newWidth)
            {
                width = newWidth;
            }
        }
    }

    comboBox.DropDownWidth = width;
}

private void cbSample_DropDown(object sender, EventArgs e)
{
    AdjustWidthComboBox(sender as ComboBox);
}

Upvotes: 0

Caladain
Caladain

Reputation: 4934

http://www.codeproject.com/KB/combobox/ComboBoxAutoWidth.aspx

That has code sample that shows how to capture the event and widen the box.

OR, you could have it as a seperate function you manually call, like this: http://weblogs.asp.net/eporter/archive/2004/09/27/234773.aspx

Upvotes: 3

Clyde
Clyde

Reputation: 8145

There is actually a DropDownWidth property that controls how wide the drop down area is. This way you can have a narrow control that doesn't take up too much space on the form, but a larger drop down area that could extend over as much of the screen as you want.

Upvotes: 4

Related Questions