0

Web ページから任意のタイプ コントロール (テキスト ボックス、ラベル、ハイパーリンクなど) のテキスト プロパティを動的に設定する必要があります。これが私のコードです

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)..
}

次のコードのように、テキストプロパティを設定するためにすべてのコントロールタイプをチェックする必要はありません

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

ありがとう

4

1 に答える 1

0

C#4.0(VS 2010)を使用している場合は、「動的」キーワードを使用できます。

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

明らかに、Textプロパティがないコントロールでこれを実行しようとすると、ランタイム例外が発生します。

于 2013-01-11T10:05:00.857 に答える