【问题标题】:Checking for the control type检查控件类型
【发布时间】:2012-07-12 15:13:16
【问题描述】:

我能够获取页面所有控件的 ID 以及它们的类型,当我打印它时在页面中显示

myPhoneExtTxt Type:System.Web.UI.HtmlControls.HtmlInputText

这是根据这段代码生成的

    foreach (Control c in page)
    {
        if (c.ID != null)
        {
            controlList.Add(c.ID +" Type:"+ c.GetType());
        }
    }

但是现在我需要检查它的类型并访问其中的文本,如果它的类型是 HtmlInput 并且我不太确定该怎么做。

喜欢

if(c.GetType() == (some htmlInput))
{
   some htmlInput.Text = "This should be the new text";
}

我该怎么做,我想你明白了吗?

【问题讨论】:

    标签: c# asp.net interface casting


    【解决方案1】:

    如果我得到你的要求,这应该就是你所需要的:

    if (c is TextBox)
    {
      ((TextBox)c).Text = "This should be the new text";
    }
    

    如果您的主要目标只是设置一些文本:

    if (c is ITextControl)
    {
       ((ITextControl)c).Text = "This should be the new text";
    }
    

    为了也支持隐藏字段:

    string someTextToSet = "this should be the new text";
    if (c is ITextControl)
    {
       ((ITextControl)c).Text = someTextToSet;
    }
    else if (c is HtmlInputControl)
    {
       ((HtmlInputControl)c).Value = someTextToSet;
    }
    else if (c is HiddenField)
    {
       ((HiddenField)c).Value = someTextToSet;
    }
    

    额外的控件/界面必须添加到逻辑中。

    【讨论】:

    • 是否包括输入类型为隐藏?
    • 不幸的是,没有。 HiddenFields 是令人讨厌的小混蛋,因为它们不会从任何有用的东西中继承,必须直接加以说明。我已经编辑了我的答案以包括支持。
    • 还可以考虑在这些类型检查中使用as 运算符。
    • @JeppeStigNielsen 我很好奇在测试如何执行单行转换与 N 次可能转换时,您将如何实现它?你会事先简单定义 N 个持有者,然后尝试为每个持有者分配并检查 null 吗?
    • 如果我们需要像这里这样的类型的优先级列表,它本身当然是一种代码味道。但我同意将aselse-if 链一起使用可能很困难。您可以将其分解为一个方法并使用return 而不是else。例如:var textControl = c as ITextControl; if (textControl != null) { textControl.Text = x; return; } var htmlInputControl = c as HtmlInputControl; if (htmlInputControl != null) { htmlInputControl.Value = x; return; }
    猜你喜欢
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2013-08-26
    • 2018-10-31
    • 2014-07-24
    • 2011-12-27
    相关资源
    最近更新 更多