How to make dropdown list wider than control's width?

  • Thread starter Thread starter Andrew
  • Start date Start date
A

Andrew

Hello, friends,

We use System.Windows.Forms.ComboBox in our c#.net 2005 app. We want to make
the dropdown list wider than the comboBox's width. (Some items in the
dropdown list have more characters that go beyond the comboBox's width).

How do we do it? Thanks a lot.
 
Hi i have this script in VB, so if you could translate, you can use it.
this code keeps the combo size, and only the dropdown list is wider than the
combo itself, and it matches the longest item in the list.

Private Function GetCboWidth(ByVal myIndex As Integer)
Dim cwidth As Long
Dim cnt As Long
Dim NumOfChars As Long
Dim LongestComboItem As Long
Dim avgCharWidth As Long
Dim NewDropDownWidth As Long


For cnt = 0 To cboCombo(myIndex).ListCount - 1
NumOfChars = SendMessage(cboCombo(myIndex).hwnd, CB_GETLBTEXTLEN, cnt,
ByVal 0)
If NumOfChars > LongestComboItem Then LongestComboItem = NumOfChars
Next

avgCharWidth = GetFontDialogUnits()

NewDropDownWidth = (LongestComboItem - 2) * avgCharWidth

Call SendMessage(cboCombo(myIndex).hwnd, CB_SETDROPPEDWIDTH,
NewDropDownWidth, ByVal 0)

cwidth = SendMessage(cboCombo(myIndex).hwnd, CB_GETDROPPEDWIDTH, 0, ByVal
0)

End Function
 
Andrew said:
Hello, friends,

We use System.Windows.Forms.ComboBox in our c#.net 2005 app. We want to
make
the dropdown list wider than the comboBox's width. (Some items in the
dropdown list have more characters that go beyond the comboBox's width).

How do we do it? Thanks a lot.

A non-pinvoke way:

private void ConfigureDropDownWindowWidth(ComboBox control)
{
int width = control.DropDownWidth;
Font f = control.Font;

using (Bitmap bmp = new Bitmap(16, 16)) {
using (Graphics canvas = Graphics.FromImage(bmp)) {
foreach (object item in control.Items) {
string s = item as string;
if (!string.IsNullOrEmpty(s)) {
// Measure the item's width.
SizeF itemSize = canvas.MeasureString(s, f);
if (width < itemSize.Width) {
width = (int) itemSize.Width;
}
}
}
}
}

if (width > control.DropDownWidth) {
// Set the width of the drop-down area.
control.DropDownWidth = width;
}
}

HTH,
Mythran
 
Back
Top