700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > C# 学习笔记(16)ComboBox下拉列表框宽度自适应

C# 学习笔记(16)ComboBox下拉列表框宽度自适应

时间:2023-08-21 21:21:15

相关推荐

C# 学习笔记(16)ComboBox下拉列表框宽度自适应

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);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。