试图以INT格式获取下拉列表的宽度

本文关键字:下拉列表 获取 格式 INT | 更新日期: 2023-09-27 18:09:22

我试图得到一个下拉列表的宽度,它一直过来与"px"在它的末尾。我想要的最终结果是确定DropDownList中所有项目的宽度,这样我就可以通过编程设置宽度。

我有:

    public static int FindTheWidth(object sender)
    {
        DropDownList senderComboBox2 = (DropDownList)sender;
        //            int width = senderComboBox.Width;
        var s = senderComboBox2.Width;
        var CBW = s.SubString(0, s.IndexOf("p"));
        int width2 = Convert.ToInt32(CBW);
        int vertScrollBarWidth = 2;
        int newWidth;
        foreach (string s in ((DropDownList)sender).Items)
        {
            newWidth = width2 + vertScrollBarWidth;
            if (width2 < newWidth)
            {
                width2 = newWidth;
            }
        }
        senderComboBox2.Width = width2;
        return width2;
    }

任何想法?

试图以INT格式获取下拉列表的宽度

代码有很多类型转换问题。

WebControl.Width.Value的类型应该是double。

((DropDownList)sender).Items的类型应该是listtitemcollection。

public static int FindTheWidth(object sender)
{
    DropDownList senderComboBox2 = (DropDownList)sender;
    var width = senderComboBox2.Width;
    double doubleValue = width.Value;
    int width2 = (int)doubleValue;
    int vertScrollBarWidth = 2;
    int newWidth;
    foreach (ListItem s in ((DropDownList)sender).Items)
    {
        newWidth = width2 + vertScrollBarWidth;
        if (width2 < newWidth)
        {
            width2 = newWidth;
        }
    }
    senderComboBox2.Width = width2;
    return width2;
}

这是我遇到过的最糟糕的逻辑,为什么要在业务层尝试表示层功能,这是这样的…这是你试图实现到服务器代码的设计问题?您可以尝试在设计结束时设置宽度。