Reputation: 189
Some of the items in my combobox are more than 20 characters long, I wrote this code to make them smaller and add "..." but it´s not working. By example instead of "comboboxitemnumberthree" it would look like this:"comboboxitemnu..." to fit the size of the combobox
i=0;
do
{
var item = comboBox1.Items[i].ToString();
if (item.Length >= 17) // not sure about this part
{
item = item.Substring(0, item.Length - 6) + "...";
}
i++;
} while (i < comboBox1.Items.Count); //finishes when theres not any other item left on the combobox
Please let me know what is wrong. Thanks in advance.
Upvotes: 0
Views: 2413
Reputation: 61
Just paste this code into the DropDown
event of ComboBox
.
Graphics g = comboBox1.CreateGraphics();
float largestSize = 0;
for (int i = 0; i < comboBox1.Items.Count; i++)
{
SizeF textSize = g.MeasureString(comboBox1.Items[i].ToString(), comboBox1.Font);
if (textSize.Width > largestSize)
largestSize = textSize.Width;
}
if (largestSize > 0)
comboBox1.DropDownWidth = (int)largestSize;
Upvotes: 6
Reputation: 606
I'm not at my machine to test but this should do what you need. Try to avoid do-while whenever possible. For maintainability.
for (int i = 0; i < combobox.Items.Count; i++) {
if (combobox.Items[i].ToString().Length > limit) {
// -3 for the ellipsis
combobox.Items[i] = String.Format(
"{0}...", combobox.Items[i].ToString().Substring(0, limit - 3)
);
}
}
EDIT: modified code. Was in Vegas at the time. ;P
Upvotes: 1
Reputation: 216243
You are not replacing the items in the combobox with the new string after the truncation
for(int x = 0; x < combobox.Items.Count; x++)
{
string item = combobox.Items[x].ToString();
if(item.Length > 17)
combobox.Items[x] = item.Substring(0,17) + "...";
}
Upvotes: 0