技术开发 频道

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


【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}
0
相关文章