How to make the combobox dropdown list resize the largest item?

I have a DataGridView with a ComboBox in it that can contain several rather large rows. Is there a way for the drop-down list to expand itself or at least write the lines so that the user can see the entire line without me to resize the ComboBox column?

+8
c # winforms combobox datagridview
source share
3 answers

Here is what I did for this, works great ...

 public class ImprovedComboBox : ComboBox { public ImprovedComboBox() { } public object DataSource { get { return base.DataSource; } set { base.DataSource = value; DetermineDropDownWidth(); } } public string DisplayMember { get { return base.DisplayMember; } set { base.DisplayMember = value; DetermineDropDownWidth(); } } public string ValueMember { get { return base.ValueMember; } set { base.ValueMember = value; DetermineDropDownWidth(); } } private void DetermineDropDownWidth() { int widestStringInPixels = 0; foreach (Object o in Items) { string toCheck; PropertyInfo pinfo; Type objectType = o.GetType(); if (this.DisplayMember.CompareTo("") == 0) { toCheck = o.ToString(); } else { pinfo = objectType.GetProperty(this.DisplayMember); toCheck = pinfo.GetValue(o, null).ToString(); } if (TextRenderer.MeasureText(toCheck, this.Font).Width > widestStringInPixels) widestStringInPixels = TextRenderer.MeasureText(toCheck, this.Font).Width; } this.DropDownWidth = widestStringInPixels + 15; } } 
+6
source share

This is a very elegant solution:

 private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e) { ComboBox senderComboBox = (ComboBox)sender; int width = senderComboBox.DropDownWidth; Graphics g = senderComboBox.CreateGraphics(); Font font = senderComboBox.Font; int vertScrollBarWidth = (senderComboBox.Items.Count>senderComboBox.MaxDropDownItems) ?SystemInformation.VerticalScrollBarWidth:0; int newWidth; foreach (string s in ((ComboBox)sender).Items) { newWidth = (int) g.MeasureString(s, font).Width + vertScrollBarWidth; if (width < newWidth ) { width = newWidth; } } senderComboBox.DropDownWidth = width; } 

Set the width of the list of comboboxes to the longest line width http://www.codeproject.com/KB/combobox/ComboBoxAutoWidth.aspx

Source: ComboBox DropDownWidth Calculation in C #

+3
source share

Not that I know, although some browsers are smart enough to expand the width of the drop-down menu beyond the width of the window if necessary. I know that Firefox and Chrome can do this if you can have a little control over your user base.

If you are really desperate, how about a flash compiler sending data back to html?

-one
source share

Source: https://habr.com/ru/post/650155/


All Articles