zoukankan      html  css  js  c++  java
  • Autowidth of ComboBox's content

    Auto-width of ComboBox's content

    回答1

    You can't use it directly.

    Do a trick

    First iterate through all items of your combobox, check for the width of every items by assigning the text to a label. Then, check width every time, if width of current item gets greater than previous items then change the maximum width.

    int DropDownWidth(ComboBox myCombo)
    {
        int maxWidth = 0;
        int temp = 0;
        Label label1 = new Label();
    
        foreach (var obj in myCombo.Items)
        {
            label1.Text = obj.ToString();
            temp = label1.PreferredWidth;
            if (temp > maxWidth)
            {
                maxWidth = temp;
            }
        }
        label1.Dispose();
        return maxWidth;           
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
        comboBox1.DropDownWidth = DropDownWidth(comboBox1);
    }
    

    OR

    As suggested by stakx, you can use TextRenderer class

    int DropDownWidth(ComboBox myCombo)
    {
        int maxWidth = 0, temp = 0;
        foreach (var obj in myCombo.Items)
        {
            temp = TextRenderer.MeasureText(obj.ToString(), myCombo.Font).Width;
            if (temp > maxWidth)
            {
                maxWidth = temp;
            }
        }
        return maxWidth;
    }
    

    回答2

    obj.ToString() doesn't work for me, I suggest to use myCombo.GetItemText(obj). This works for me:

    private int DropDownWidth(ComboBox myCombo)
    {
        int maxWidth = 0, temp = 0;
        foreach (var obj in myCombo.Items)
        {
            temp = TextRenderer.MeasureText(myCombo.GetItemText(obj), myCombo.Font).Width;
            if (temp > maxWidth)
            {
                maxWidth = temp;
            }
        }
        return maxWidth + SystemInformation.VerticalScrollBarWidth;
    }
    

    自己处理的,综合上面两个

     private void SetComboBoxWidth(ComboBox comboBox)
            {
                int maxWidth = 260;
                foreach (var obj in comboBox.Items)
                {
                    var temp = TextRenderer.MeasureText(comboBox.GetItemText(obj), comboBox.Font).Width;
                    if (temp > maxWidth)
                    {
                        maxWidth = temp;
                    }
                }
    
                comboBox.Width = maxWidth + SystemInformation.VerticalScrollBarWidth;
            }
  • 相关阅读:
    简单的嵌套循环
    七、 二进制位运算
    六、字符串格式化--------列表常用操作
    JavaScript取消默认控件并添加新控件(DOM编程艺术第11章)
    JavaScript 字符串拼接 & setInterval()实现简单动画
    伪站创建代码-山东理工
    CSS常用样式
    CSS基础知识
    HTML5其他标签应用
    HTML表单的应用
  • 原文地址:https://www.cnblogs.com/chucklu/p/15668692.html
Copyright © 2011-2022 走看看