当前位置:IT168首页 > 技术开发 > 概述
[收藏此页] [打印] [推荐] [评论]

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

责任编辑:nancy作者:ITPUB论坛   2008-07-07   
【内容导航】
文本Tag: 微软 sql

【IT168技术文档】

  如果能够让下拉列表的宽度随着内容的变化而变化,这个问题不就解决了。下面我们看看如何让ComboBox的下拉列表宽度自适应内容的宽度:
1private void AdjustComboBoxDropDownListWidth(object comboBox) 2{ 3 Graphics g = null; 4 Font font = null; 5 try 6 { 7 ComboBox senderComboBox = null; 8 if (comboBox is ComboBox) 9 senderComboBox = (ComboBox)comboBox; 10 else if (comboBox is ToolStripComboBox) 11 senderComboBox = ((ToolStripComboBox)comboBox).ComboBox; 12 else 13 return; 14 15 int width = senderComboBox.Width; 16 g = senderComboBox.CreateGraphics(); 17 font = senderComboBox.Font; 18 19 //checks if a scrollbar will be displayed. 20 //If yes, then get its width to adjust the size of the drop down list. 21 int vertScrollBarWidth = 22 (senderComboBox.Items.Count > senderComboBox.MaxDropDownItems) 23 ? SystemInformation.VerticalScrollBarWidth : 0; 24 25 int newWidth; 26 foreach (object s in senderComboBox.Items) //Loop through list items and check size of each items. 27 { 28 if (s != null) 29 { 30 newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width 31 + vertScrollBarWidth; 32 if (width < newWidth) 33 width = newWidth; //set the width of the drop down list to the width of the largest item. 34 } 35 } 36 senderComboBox.DropDownWidth = width; 37 } 38 catch 39 { } 40 finally 41 { 42 if (g != null) 43 g.Dispose(); 44 } 45}
上一页
1
2下一页
收藏到: 添加到“百度搜藏”添加到“QQ书签”添加到“Google书签”添加到“Yahoo收藏”添加到“和讯网摘”
【内容导航】
本文欢迎转载,转载请注明:转载自IT168 [ http://www.it168.com/ ]
本文链接:http://tech.it168.com/d/2008-07-07/200807071557784.shtml
技术开发相关文章  
  • 暂无
友情推介