检查控件类型

use*_*156 16 c# asp.net casting interface

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

myPhoneExtTxt Type:System.Web.UI.HtmlControls.HtmlInputText
Run Code Online (Sandbox Code Playgroud)

这是基于此代码生成的

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

但现在我需要检查它的类型并访问其中的文本,如果它的类型为HtmlInput,我不太清楚如何做到这一点.

喜欢

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

我怎么能这样做,我想你明白了吗?

Jai*_*res 37

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

if (c is TextBox)
{
  ((TextBox)c).Text = "This should be the new text";
}
Run Code Online (Sandbox Code Playgroud)

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

if (c is ITextControl)
{
   ((ITextControl)c).Text = "This should be the new text";
}
Run Code Online (Sandbox Code Playgroud)

为了支持隐藏字段:

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;
}
Run Code Online (Sandbox Code Playgroud)

必须将额外的控件/接口添加到逻辑中.