C# 检查控件类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11459135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:56:04  来源:igfitidea点击:

Checking for the control type

c#asp.netinterfacecasting

提问by user1416156

I am able to get the IDs of all the controls of a page and also their type, in the page when i print it it shows

我可以在打印页面时获取页面中所有控件的 ID 以及它们的类型

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

this is generated based on this code

这是基于此代码生成的

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

But now i need to check its type and access the text in it if its of type HtmlInput and i am not quite sure how to do that.

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

Like

喜欢

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

how can i do this, i think you get the idea?.

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

采纳答案by Jaime Torres

This should be all you need if I get what you're asking:

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

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

If your primary goal is to just set some text:

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

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

In order to support a hidden field as well:

为了也支持隐藏字段:

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;
}

Additional controls/interfaces would have to be added to the logic.

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