您的位置:首页 > 编程语言 > C#

c#动态设置combobox控件下拉项宽度以实现下拉项文字可以完全显示。

2009-01-07 17:15 1096 查看
c#动态设置combobox控件下拉项宽度以实现下拉项文字可以完全显示。

这个几乎是来自这里的啊: http://blog.csdn.net/ccy3253/archive/2008/01/26/2067304.aspx
0.控件类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class CtrlComboBox :ComboBox
{
protected override void OnDropDown(EventArgs e)
{
base.OnDropDown(e);
AdjustComboBoxDropDownListWidth(); //调整comboBox的下拉列表的大小
}

private void AdjustComboBoxDropDownListWidth()
{
Graphics g = null;
Font font = null;
try
{
int width = this.Width;
g = this.CreateGraphics();
font = this.Font;

//checks if a scrollbar will be displayed.
//If yes, then get its width to adjust the size of the drop down list.
int vertScrollBarWidth =
(this.Items.Count > this.MaxDropDownItems)
? SystemInformation.VerticalScrollBarWidth : 0;

int newWidth;
foreach (object s in this.Items) //Loop through list items and check size of each items.
{
if (s != null)
{
//newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width
newWidth = (int)g.MeasureString(((ComboBoxData)s).StrText, font).Width
+ vertScrollBarWidth;
if (width < newWidth)
width = newWidth; //set the width of the drop down list to the width of the largest item.
}
}
this.DropDownWidth = width;
}
catch
{ }
finally
{
if (g != null)
g.Dispose();
}
}
}
}

1.数据源类
public class ComboBoxData
{
private string _StrValue;
private string _StrText;

public ComboBoxData(string StrValue, String StrText)
{
_StrText = StrText;
_StrValue = StrValue;

}

public string StrValue
{
get
{
return _StrValue;
}
set
{
_StrValue = value;
}
}

public string StrText
{
get
{
return _StrText;
}
set
{
_StrText = value;
}
}

}

2.form 里使用它。

ArrayList al = new ArrayList();
for (int i = 0; i < 9; i++)
{
al.Add( new ComboBoxData("aaaaaaaaaaaaaaaaaaa" + i.ToString(), "aaaaaaaaaaaaaaaaaaa" + i.ToString()));
}
al.Add(new ComboBoxData("只要在我们向combox添加完所有项后,调用一下,就可以调整comboBox下拉列表的宽度了", "只要在我们向combox添

加完所有项后,调用一下,就可以调整comboBox下拉列表的宽度了"));
ctrlComboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
ctrlComboBox1.DisplayMember = "StrText";
ctrlComboBox1.ValueMember = "StrValue";
ctrlComboBox1.DataSource = al;

如果想实现在选择了某项后,combobox以提示的方式来查看选择项的完全text,那要加一个toolTip

private void comboBox1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
this.toolTip1.SetToolTip(this.comboBox1, this.comboBox1.Text);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐