2016-12-29 45 views
0

天冬氨酸:代碼如何訪問靜態方法內的Asp控件?

<asp:TextBox ID="TextBox1" runat="server" ReadOnly="true"></asp:TextBox> 
<asp:TextBox ID="TextBox2" runat="server" ReadOnly="true"></asp:TextBox> 

C#:

[System.Web.Services.WebMethod] 
public static Array LoadAssetAssignView() { 
string sql = "SELECT Time,Inuse FROM table4"; 
using(SqlConnection Connection = new SqlConnection((@ "Data Source"))) { 
    using(SqlCommand myCommand = new SqlCommand(sql, Connection)) { 
    Connection.Open(); 
    using(SqlDataReader myReader = myCommand.ExecuteReader()) { 
    DataTable dt = new DataTable(); 
    dt.Load(myReader); 
    Connection.Close(); 
    Num1 = textbox1.text; //Error(Can't access my asp control) 
    Num2 = textbox2.text; 
    } 
    } 
} 
} 

在我的ASP頁我涉及到兩個文本框爲我requirement.But在我的後端,我不能在靜態方法來訪問文本框。建議一些想法。答案而不是評論被讚賞。

+2

使其非靜態 – Backs

+0

[如何訪問ASP.net中的靜態方法內的頁面控件]可能的副本(http://stackoverflow.com/questions/31514188/how-to-access-page-controls-內部靜態方法在ASP網) – Danieboy

+0

你不能在web服務中使用控件。如果我沒有錯,你正嘗試在Web服務中使用它。而不是直接將值作爲參數傳遞給方法 –

回答

4

試試看!

[System.Web.Services.WebMethod] 
      public static Array LoadAssetAssignView() 
       { 
       string sql = "SELECT Time,Inuse FROM table4"; 
       using (SqlConnection Connection = new SqlConnection((@"Data Source"))) 
        { 
        using (SqlCommand myCommand = new SqlCommand(sql, Connection)) 
         { 
          Connection.Open(); 
          using (SqlDataReader myReader = myCommand.ExecuteReader()) 
          { 
           DataTable dt = new DataTable(); 
           dt.Load(myReader); 
           Connection.Close(); 
           Page page = (Page)HttpContext.Current.Handler; 
           TextBox TextBox1 = (TextBox)page.FindControl("TextBox1"); 
           TextBox TextBox2 = (TextBox)page.FindControl("TextBox2"); 
           Num1=TextBox1 .text; 
           Num2=TextBox2 .text; 
        } 
       } 
      } 
     } 

請參閱this