首页 > 解决方案 > 在 datagridviewcombobox 中将 combobox.dropdownwidth 设置为最大宽度的问题

问题描述

我有一个 datagridview 组合框列。我需要将组合框的宽度动态调整为最长的字符串宽度,以便用户可以读取组合框项中的冗长字符串。我的代码是

            int width = comboBox.DropDownWidth;
            Graphics g = comboBox.CreateGraphics();
            Font font = comboBox.Font;
            int vertScrollBarWidth =
                (comboBox.Items.Count > comboBox.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;
                }
            }
            comboBox.DropDownWidth = width;

但这不起作用。我认为代码没有任何问题,但宽度仍然没有改变。我是否必须更改 datagridview 的任何属性才能更改宽度?

标签: c#winformsdatagridviewcombobox

解决方案


推荐阅读