Search code examples
c#winformsdatagridviewcomboboxdatagridviewcombobox

How to make the ComboBox drop down list resize itself to fit the largest item?


I've got a DataGridView with a ComboBox in it that might contain some pretty large strings. Is there a way to have the drop down list expand itself or at least wordwrap the strings so the user can see the whole string without me having to resize the ComboBox column width?


Solution

  • Here's what I did to solve 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;
        }
    }