2016-09-08 5 views
1

私はブートストラップアラートを使用していますが、コード内の静的メソッドからアラートクラスを変更しようとしていますが、エラーが発生しています:C#HtmlGenericControlエラー静的メソッドから

非静的フィールドにはオブジェクト参照が必要です。

イムかなり新しいこのように任意のヘルプははるかに高く評価されるだろう

aspx.csへ:

public static void alert() 
{ 
    wallboardAlert.Visible = alertVisable; 
    wallboardAlert.Attributes["class"] = alertClassType; 
} 

.aspxの

<div class="" id="wallboardAlert" runat="server"> 
    <h1 id="wallboardAlertTitle" runat="server"><strong></strong></h1> 
    <h4 id="wallboardAlertBody" runat="server"></h4> 
</div> 
+0

宣言から 'static'を削除するだけです。 'wallboardAlert'はあなたのページクラスで定義されており、インスタンスメソッドからアクセスする必要があります。 –

+0

またはhttp://stackoverflow.com/questions/14684974/asp-net-access-a-control-from-static-function –

+0

私は宣言から静的メソッドを呼び出すクラスは、動作しません – user3362804

答えて

0

あなたが保持するための静的変数を定義することができますフォームの現在のインスタンス:

private static MyFormClassName currentForm = null; // Use the real class name 

protected override void OnInit(EventArgs e) 
{ 
    currentForm = this; 
    base.OnInit(e); 
} 

静的関数は、フォームとそのコントロールにアクセスするには、その変数を使用することができます。

public static void alert() 
{ 
    if (currentForm != null) 
    { 
     currentForm.wallboardAlert.Visible = currentForm.alertVisable; 
     currentForm.wallboardAlert.Attributes["class"] = currentForm.alertClassType; 
    } 
} 

これは、静的な関数が呼び出されたときに、フォームのインスタンスが存在する場合にのみ動作しますのでご注意ください。

関連する問題