【发布时间】:2010-12-15 09:38:34
【问题描述】:
我有一个DataGridView,其中有一个ComboBox,其中可能包含一些相当大的字符串。有没有办法让下拉列表自行扩展或至少对字符串进行自动换行,这样用户就可以看到整个字符串,而无需我调整ComboBox 列宽的大小?
【问题讨论】:
标签: c# winforms datagridview combobox datagridviewcombobox
我有一个DataGridView,其中有一个ComboBox,其中可能包含一些相当大的字符串。有没有办法让下拉列表自行扩展或至少对字符串进行自动换行,这样用户就可以看到整个字符串,而无需我调整ComboBox 列宽的大小?
【问题讨论】:
标签: c# winforms datagridview combobox datagridviewcombobox
这是一个非常优雅的解决方案:
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 senderComboBox.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
【讨论】:
这是我为解决这个问题所做的,效果很好......
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;
}
}
【讨论】:
DataSourceChanged、ValueMemberChanged 和DisplayMemberChanged 事件而不是隐藏属性可能是一个更好的主意。
base.OnDropDown(e) 之前为OnDropDown 添加一个覆盖以在其中添加调用。顺便说一句,对于最后的if > 检查,只需将该宽度存储在一个变量中,而不是调用该计算两次。
if (this.Items.Count * this.ItemHeight > this.DropDownHeight) widestStringInPixels += SystemInformation.VerticalScrollBarWidth;
据我所知,虽然有些浏览器足够智能,可以在需要时将下拉菜单的宽度扩展到框的宽度之外。我知道如果你能稍微控制你的用户群,Firefox 和 Chrome 就可以做到。
如果您真的很绝望,那么基于 Flash 的组合框将数据发送回 html 怎么样?
【讨论】: