【问题标题】:How to access the Asp Controls inside a Static Method?如何访问静态方法中的 Asp 控件?
【发布时间】:2016-12-29 07:23:31
【问题描述】:

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 页面中,我涉及两个文本框以满足我的要求。但在我的后端,我无法以静态方法访问文本框。建议一些想法。感谢回答而不是评论。

【问题讨论】:

  • 使其非静态
  • 您不能在 web 服务中使用控件。如果我没记错的话,您正在尝试在 Web 服务中使用它。而不是直接将值作为方法中的参数传递
  • 您无法访问网络方法中的任何控件。您可以将文本框的值作为静态方法的参数传递。

标签: c# asp.net


【解决方案1】:

试试这个!

 [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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 2013-04-18
    相关资源
    最近更新 更多