我有一个DataGridView
,其中ComboBox
可能包含一些非常大的字符串。有没有办法让下拉列表自行扩展或者至少自动换行字符串,这样用户就可以看到整个字符串而不必调整ComboBox
列宽?
答案 0 :(得分:7)
以下是我为解决这个问题所做的工作,效果很好......
public class ImprovedComboBox : ComboBox
{
public ImprovedComboBox()
{
}
public object DataSource
{
get { return base.DataSource; }
set { base.DataSource = value; DetermineDropDownWidth(); }
}
public string DisplayMember
{
get { return base.DisplayMember; }
set { base.DisplayMember = value; DetermineDropDownWidth(); }
}
public string ValueMember
{
get { return base.ValueMember; }
set { base.ValueMember = value; DetermineDropDownWidth(); }
}
private void DetermineDropDownWidth()
{
int widestStringInPixels = 0;
foreach (Object o in Items)
{
string toCheck;
PropertyInfo pinfo;
Type objectType = o.GetType();
if (this.DisplayMember.CompareTo("") == 0)
{
toCheck = o.ToString();
}
else
{
pinfo = objectType.GetProperty(this.DisplayMember);
toCheck = pinfo.GetValue(o, null).ToString();
}
if (TextRenderer.MeasureText(toCheck, this.Font).Width > widestStringInPixels)
widestStringInPixels = TextRenderer.MeasureText(toCheck, this.Font).Width;
}
this.DropDownWidth = widestStringInPixels + 15;
}
}
答案 1 :(得分:6)
这是非常优雅的解决方案:
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;
}
调整组合框下拉列表宽度到最长字符串宽度 http://www.codeproject.com/KB/combobox/ComboBoxAutoWidth.aspx
答案 2 :(得分:-2)
不是我所知道的,虽然有些浏览器足够聪明,如果需要,可以将下拉菜单的宽度扩展到超出框的宽度。我知道如果你能够稍微控制你的用户群,Firefox和Chrome就可以做到这一点。
如果你真的很绝望,基于闪存的组合框如何将数据发回html?