Click here to Skip to main content
Email Password   helpLost your password?

Sample Image - ComboBoxAutoWidth.jpg

Introduction

This small snippet of code will show you how to automatically adjust the size of the drop down list of a combo box to fit the size of the longest string in its items.

Code

Step 1: Add an event handler for the DropDown event of the combo box. Call it AdjustWidthComboBox_DropDown for the sake of the following code.

Step 2: Add the following event handler code.

private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e)
{
    ComboBox senderComboBox = (ComboBox)sender;
    int width = senderComboBox.DropDownWidth;
    Graphics g = senderComboBox.CreateGraphics();
    Font font = senderComboBox.Font;
    int vertScrollBarWidth = 
        (senderComboBox.Items.Count>senderComboBox.MaxDropDownItems)
        ?SystemInformation.VerticalScrollBarWidth:0;

    int newWidth;
    foreach (string s in ((ComboBox)sender).Items)
    {
        newWidth = (int) g.MeasureString(s, font).Width 
            + vertScrollBarWidth;
        if (width < newWidth )
        {
            width = newWidth;
        }
    }
    senderComboBox.DropDownWidth = width;
}

Explanation

The code assumes that the handler is only for a ComboBox and does a cast without checking the type of the sender.

It then gets the Graphics and Font objects for the combo box which will help us to measure the size of the string in the list.

senderComboBox.Items.Count>senderComboBox.MaxDropDownItems checks whether a scrollbar will be displayed. If it is going to be displayed, then we get its width to adjust the size of the drop down list accordingly.

We then scroll through the list of items checking the size of each item and finally setting the width of the drop down list to the width of the largest item including scroll bar width.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralUsing extension method
C#rizje
6:05 31 May '09  
Hi All,

You can use an extension method so you don't have to rewrite the samecode for all your ComboBoxes

ExtensionMethods.cs

using System;
using System.Linq;
using System.Windows.Forms;

namespace MyNamespace
{
public static class ExtensionMethods
{
/// <summary> /// Autosizes the width of the size drop down.
/// </summary> /// <param name="sender">The sender.</param> public static void AutoSizeDropDownWidth(this ComboBox sender)
{
if (sender.Items.Count == 0)
{
sender.DropDownWidth = sender.Width;
return;
}

var comboBoxItems = new object[sender.Items.Count];
sender.Items.CopyTo(comboBoxItems, 0);

using (var graphics = sender.CreateGraphics())
{
var largestItem = (from width in (from item in comboBoxItems
select Convert.ToInt32(graphics.MeasureString(item.ToString(), sender.Font).Width))
select width).Max();

sender.DropDownWidth = largestItem > sender.Width ? largestItem : sender.Width;
}
}
}
}

now the only thing you need to call is

private void comboBoxTypes_DropDown(object sender, EventArgs e)
{
comboBoxTypes.AutoSizeDropDownWidth();
}

QuestionCode
DanielHH
8:01 28 Apr '09  
Could you please send me the code to daniel_h_hernandez@msn.com

Thanks in advance,
Daniel

Daniel HH

GeneralOn which event we have to bind?
harshkapoors
5:11 19 Apr '09  
Hi SathishVJ,

Its a very good article, most of the developer faces this issue. after reading your article but i couldn't implement the same. i have to ask that
On which event we have to bind this? because i have used on OnLoad event but it didn't work.
So, Please mention the event name as well as aspx code for the same. so that i can implement the same.
Your reply will be helpful for me.

Thanks & Regards
Harsh
GeneralPlz provide sorce code for this article..
Member 3259177
3:38 10 Jan '09  
hi
can u plz provide sample source code for this article..

Thanks iam waitng for ur reply...

ramesh n

ramesh

GeneralSuggestion: Don't assign DropDownWidth to variable 'width'
qian_xu
17:54 31 Oct '07  
If the items of the combobox are created dynamically, for the better don't assign senderComboBox.DropDownWidth to variable 'width'. If the new string's length is shorter than the old one's, the drop down list length would be too long.

qian_xu
GeneralCouple of suggestions
CleaKO
11:01 30 Mar '07  
I would suggest that you also set the ComboBox.Width property, that way the drop down matches the width of the box it is coming from. Also, if you add a little bit to the width, like 5 or so, it will take into account the button at the end of the box.

Otherwise, Im glad I could find this, I had this code but it is somewhere else.


CleaKO

"I think you'll be okay here, they have a thin candy shell. 'Surprised you didn't know that.'" - Tommy (Tommy Boy)
"Fill it up again! Fill it up again! Once it hits your lips, it's so good!" - Frank the Tank (Old School)

GeneralDropDown list width increment according to the value in list
vinodgn
19:28 4 Nov '06  
I want to know if this method can work with a DropDownList instead of a combo box. It would be very kindful of you if you could suggest me some solution. Its really very urgent.




Vinod G Nair

GeneralRe: DropDown list width increment according to the value in list
CleaKO
10:59 30 Mar '07  
A DropDownList is the same thing as a combobox in the sense of a Windows App. When speaking about a web application, though, a DropDownList autosizes itself.


CleaKO

"I think you'll be okay here, they have a thin candy shell. 'Surprised you didn't know that.'" - Tommy (Tommy Boy)
"Fill it up again! Fill it up again! Once it hits your lips, it's so good!" - Frank the Tank (Old School)

GeneralProblem with foreign language (non-English)
KiTsuNeKo
23:22 10 Nov '05  
This does work for English, but not for other language font. It seems like the newWidth measured from other language characters are less than the actual appearance. For example, i added Thai-language items into a combobox which has a width of 121. The max width of the items measured from the code is 119 but its length actually exceeds (it appears to exceed) the width of the combobox. Any suggestion on this issue please?...

One way i'm trying to do is adding more length for the new width but don't know how many pixel or how many percentage to add... T-T

BTW, i added this line of code after measuring the newWidth:
newWidth = (int)((double)newWidth * 1.25);

KiT
GeneralDropDownList
DoomKickYourAss
6:26 11 Aug '05  
I just want to know if this method can work with a DropDownList instead of a combo box. If yes, wich EventHandler i must use because the event DropDown doesn't exist ?

Thanks a lot Confused
GeneralVB.Net Code
alardaen
3:50 21 May '05  
Here is the vb.net code, I used the developerfusion.com converterSuspicious

Private Sub AdjustWidthComboBox_DropDown(ByVal sender As Object, ByVal e As System.EventArgs)
Dim senderComboBox As ComboBox = CType(sender, ComboBox)
Dim width As Integer = senderComboBox.DropDownWidth
Dim g As Graphics = senderComboBox.CreateGraphics
Dim font As Font = senderComboBox.Font
Dim vertScrollBarWidth As Integer = Microsoft.VisualBasic.IIf((senderComboBox.Items.Count > senderComboBox.MaxDropDownItems),SystemInformation.VerticalScrollBarWidth,0)
Dim newWidth As Integer
For Each s As String In CType(sender, ComboBox).Items
newWidth = CType(g.MeasureString(s, font).Width, Integer) + vertScrollBarWidth
If width < newWidth Then
width = newWidth
End If
Next
senderComboBox.DropDownWidth = width
End Sub

Suspicious

Alardaen
http://www.gvilas.com
Generalcustom Validator in asp .net
Dhananjaneyulud
1:45 13 Dec '04  
I want brief explanation on custom validations in asp .net with a small example
GeneralOnly calculate when filling combobox
alcoh
2:36 30 Nov '04  
Hi,

the code is nice and usefull, but I think it would be better if you only calculate the width when the combobox gets filled instead of doing the always in the OnDrop event.

You could add a flag in the eventhandler or whatever.

But anyhow, it's nice (I used it Poke tongue )
thanks,

regards,
Ike
GeneralAllow ComboItem to be an object...
ezanker
12:11 15 Jan '04  
Very Nice Cool

To make the code a little more general, allow the combo items to be objects and use combobox.GetItemText(Item) to get the string to measure:

foreach (Object s in senderComboBox.Items)
{
string ss = senderComboBox.GetItemText(s);
newWidth = (int)g.MeasureString(ss, font).Width
+ vertScrollBarWidth;
etc.

Thanks for the code and a useful, simple trick.

GeneralRe: Allow ComboItem to be an object...
oscar ho
11:22 19 Jan '04  
Hello, everyone

Good afternoon, would you mind to tell me, is it work in the ASP.NET Web Page or only work in the .Net windows, if it can use in the ASP.NET, please advise me how to use or call or what ever to use it.

Thank you very much.
Oscar
GeneralNot working inside OnDropDown
Srinivaasan M
22:11 13 Jan '04  
If the feature is added as it in the article, it is working fine.
I have tried to encapsulate this functionality by extending the ComboBox , the code should go to OnDropDown protected method. I have used the code

using System.Drawing; //add it in the top of the code

protected override void OnDropDown(EventArgs e)
{
int width = this.DropDownWidth;
Graphics g = this.CreateGraphics();
Font font = this.Font;
int vertScrollBarWidth =
(this.Items.Count > this.MaxDropDownItems)
?SystemInformation.VerticalScrollBarWidthBlush ;

int newWidth;
foreach (string s in this.Items)
{
newWidth = (int) g.MeasureString(s, font).Width
+ vertScrollBarWidth;
if (width < newWidth )
{
width = newWidth;
}
}
this.DropDownWidth = width;
base.OnDropDown(e);
}

The code fails to compile and gives the error messages
'System.Drawing.Graphics' is inaccessible due to its protection level
'System.Drawing.Font' is inaccessible due to its protection level

The compiler is not allowing creating Graphics and Font objects inside the entire class. Please send your ideas to solve the problem.



Thanks,
-Srinivaasan
GeneralRe: Not working inside OnDropDown
SathishVJ
7:09 14 Jan '04  
I tried your code in a couple of ways and it works perfectly fine. Mebbe there is something here that I do not see.

Tried mailing u code that works for me but ur mailbox is full.

~/sathishvj
GeneralRe: Not working inside OnDropDown
Surendran1
22:04 26 Apr '09  
can you please send me the code to my mail id : surendran.u@gmail.com
GeneralAny Chance
Geovani
2:08 13 Jan '04  
Any chance you could publish the code in VB?
GeneralRe: Any Chance
SathishVJ
7:12 14 Jan '04  
Sorry, I don't have VB. Hopefully somebody else will help u with this.

~/sathishvj
GeneralVB.Net Code
jasonallenbell
10:16 28 Mar '07  
This is what I use, and is based off some code by Erik Porter and others:

Public Sub RecalculateDropDownBoxWidth()
' Just reset if there are no items
If Me.Items.Count = 0 Then
Me.DropDownWidth = Me.Width
Return
End If

Dim g As Graphics = Me.CreateGraphics()
Dim WidestWidth As Integer = 0
Dim ValueToMeasure As String
Dim CurrentWidth As Integer
Dim LeftCorner As Integer

' Find the longest string
For i As Integer = 0 To Me.Items.Count - 1
ValueToMeasure = Me.GetItemText(Me.Items(i))
CurrentWidth = CType(g.MeasureString(ValueToMeasure, Me.Font).Width, Integer)
WidestWidth = Math.Max(CurrentWidth, WidestWidth)
Next

' Add a little space for a scroll bar
If Me.Items.Count > Me.MaxDropDownItems Then
WidestWidth += SystemInformation.VerticalScrollBarWidth
End If

' Make sure we don't go off the screen
LeftCorner = Me.PointToScreen(New Point(0, Me.Left)).X
WidestWidth = Math.Min(Screen.PrimaryScreen.WorkingArea.Width - LeftCorner, WidestWidth)

Me.DropDownWidth = Math.Max(WidestWidth, Me.Width)

g.Dispose()
End Sub
GeneralThis is so useful!
ilyah
13:17 8 Jan '04  
Thanks so much. Dropdowns that were not wide enough have bothered me greatly for a while now.
GeneralI agree with you
netscout
15:42 8 Jan '04  
It's idea so good~!

I'm a ultra elementary programmer~ hahaha>_<
GeneralRe: This is so useful!
Jcxl
22:56 22 Feb '04  
Agree with u~~~very good]

Wink ;)


Last Updated 8 Jan 2004 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010