如何从网页动态设置任何类型的web控件的文本属性

本文关键字:web 控件 文本 属性 类型 任何 网页 动态 设置 | 更新日期: 2023-09-27 17:51:15

我需要为任何类型控件设置文本属性(例如:文本框,标签,超链接…等)从我的网页动态。这是我的代码

foreach (string id in List<IdCollection>)
{
Control ctrl = (this.Page.FindControl(id)); // Control should be HtmlGenericControl or WebControl.
ctrl.Text=???(This property is not available for Control Class)..
}

我不需要检查每个控件类型的set text属性,就像下面的代码

if(ctrl is TextBox)
{
((TextBox)ctrl).Text="test";
}

 if(ctrl.GetType()==typeof(TextBox))
{
 ((TextBox)ctrl).Text="test";
}

是否有其他的方法来设置文本属性一样简单,就像代码

WebControl wbCntrl=(WebControl)ctrl;
wbCntrl.Tooltip="tooltip"; //// This is possible
wbCntrl.Text="test" ??? //// But this is not possible

谢谢

如何从网页动态设置任何类型的web控件的文本属性

如果你使用的是c# 4.0 (VS 2010),那么你可以使用"dynamic"关键字:

foreach (string id in List<IdCollection>)
{
  dynamic ctrl = (this.Page.FindControl(id)); 
  ctrl.Text = "test";
}

显然,你会得到一个运行时异常,如果你试图这样做的控件,没有文本属性