c# - 如何在静态方法中访问 Asp 控件?

标签 c# asp.net

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

最佳答案

试试这个!

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

关于c# - 如何在静态方法中访问 Asp 控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41374996/

相关文章:

c# - Interlocked.CompareExchange 如果不相等?

c# - 为什么这会出现在我的 C# 字符串 : £ 中

c# - 'this'在C#语言中有什么用?

c# - 向用户发送电子邮件以重置密码

asp.net - 一个小但恼人的问题——为什么 ASP.Net 将 SQL Server Guids 设置为小写?

c# - 加密 Web.Config (Web.Release.config) 使用 aspnet_regiis 转换文件

c# - 将 XML 反序列化为类

c# - Entity Framework 添加不在数据库表中的属性时列名无效

asp.net - ASP.NET 中的 MembershipProvider

javascript - IE问题: disable linkbutton onclientclick and continue doing the onclick function