您的位置:首页 > 其它

如何让ComboBox的下拉列表宽度自适应内容的宽度

2008-07-06 21:30 591 查看
在Win Form编程中,ComboBox是我们经常用到的控件,往往因为界面排版或者其它原因,ComboBox的宽度受到限制,而下拉列表中的内容太长。
如果按照ComboBox的默认设置
,下拉列表和ComboBox的宽度一样,并不会跟随内容的变化而变化,这就造成下拉列表中有些项的内容太长而不能全部显示出来,就是下面这个样子:
private void AdjustComboBoxDropDownListWidth(object comboBox)
2using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Drawing;
5using System.Data;
6using System.Text;
7using System.Windows.Forms;
8
9namespace WindowsApplication2
10 class MyComboBox : ComboBox
12 protected override void OnDropDown(EventArgs e)
14 base.OnDropDown(e);
16 AdjustComboBoxDropDownListWidth(); //调整comboBox的下拉列表的大小
17 }
18
19 private void AdjustComboBoxDropDownListWidth()
20 Graphics g = null;
22 Font font = null;
23 try
24 int width = this.Width;
26 g = this.CreateGraphics();
27 font = this.Font;
28
29 //checks if a scrollbar will be displayed.
30 //If yes, then get its width to adjust the size of the drop down list.
31 int vertScrollBarWidth =
32 (this.Items.Count > this.MaxDropDownItems)
33 ? SystemInformation.VerticalScrollBarWidth : 0;
34
35 int newWidth;
36 foreach (object s in this.Items) //Loop through list items and check size of each items.
37 if (s != null)
39 newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width
41 + vertScrollBarWidth;
42 if (width < newWidth)
43 width = newWidth; //set the width of the drop down list to the width of the largest item.
44 }
45 }
46 this.DropDownWidth = width;
47 }
48 catch
49 finally
51 if (g != null)
53 g.Dispose();
54 }
55 }
56 }
57}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐