C# 学习笔记(16)ComboBox下拉列表框宽度自适应
当下拉列表框中内容宽度大于下拉列表框宽度时
下拉列表框不能将内容全部显示出来
可以在下拉时,对下拉列表框内容进行重绘
/// <summary>/// 列表项下拉窗口宽度自适应/// </summary>/// <param name="comboBox"></param>private void AdjustComboBoxDropDownListWidth(object comboBox){Graphics g = null;Font font = null;try{ComboBox senderComboBox = null;if (comboBox is ComboBox)senderComboBox = (ComboBox)comboBox;else if (comboBox is ToolStripComboBox)senderComboBox = ((ToolStripComboBox)comboBox).ComboBox;elsereturn;int width = senderComboBox.Width;g = senderComboBox.CreateGraphics();font = senderComboBox.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 =(senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)? SystemInformation.VerticalScrollBarWidth : 0;int newWidth;foreach (object s in senderComboBox.Items) //Loop through list items and check size of each items.{if (s != null){newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width+ vertScrollBarWidth;if (width < newWidth)width = newWidth; //set the width of the drop down list to the width of the largest item.}}senderComboBox.DropDownWidth = width;}catch{}finally{if (g != null)g.Dispose();}}private void comboBox1_DropDown(object sender, EventArgs e){AdjustComboBoxDropDownListWidth(comboBox1);}