This last night I worked on a bug where I had a ToolStripComboBox in a Visual Studio custom tool window that holds a list of files but would cut off the filenames in the dropdown list if the paths became too long.
Easy enough to fix, or so I thought. After trying out about all of the property setting combinations I could think of, I never could get the control to automatically size the dropdown list width to accommodate the widest item currently in the list. This is sort of ridiculous, in my opinion, but I could not find a way to do this without writing some code to do it.
Here is the code that I wrote so hopefully someone will save some time by seeing this and not spend their Friday night on search engines and MSDN attempting to find a way to accomplish the goal:
int i = cboFile.Items.Add(file);
//make sure dropdownlist width is sized correctly
Graphics g = cboFile.ComboBox.CreateGraphics();
SizeF size = g.MeasureString(file, new Font(cboFile.Font.FontFamily.Name, cboFile.Font.Size));
// Set the DropDownWidth if the item has a greater width
int itemWidth = (int)size.Width + 10; //add a little empty space
if (itemWidth > cboFile.DropDownWidth)
cboFile.DropDownWidth = itemWidth;
You can ignore the definition of "i", I was using that later in the code to do some processing specific to my extension. It is possible that there is an easier way to do this, but I couldn’t find one.