如何访问静态方法中的Asp控件?

时间:2016-12-29 07:23:32

标签: c# asp.net

天冬氨酸:代码

<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页面中,我参与了两个文本框。但是在我的后端,我无法访问静态方法中的文本框。建议一些想法。答案而不是评论被赞赏。

1 个答案:

答案 0 :(得分:7)

试试吧!

 [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