CS0120:非静态字段、方法或 属性“_Default.txtEditValue”需要对象引用

CS0120: An object reference is required for the non-static field, method, or property '_Default.txtEditValue'

当我单击一个按钮时,它会获取该按钮的值 (Id) 并将其传递给页面后面的代码

----Ajax代码------

.ajax({
            type: "POST",
            url: "CS.aspx/Edit", 
            data: "{'dt1':'" + dt1 +"'}",
            contentType: "application/json; charset=utf-8",
            dataType:"json", 
            success: function(result)
             {
                alert(result.d);
             }
        });

编辑是我在页面后面的代码中使用的方法

----code behind page code------

public static string Edit(string dt1)
{
    string pcId = dt1;
    NpgsqlConnection conn = new NpgsqlConnection("Server=192.168.0.133;User Id=123; " + "Password=123;Database=checDB;"); 
    try
     {
            conn.Open(); 
            NpgsqlCommand command = new NpgsqlCommand("select Center_Id,center_Name from tbl_Profit_Centers where Center_Id = " + pcId, conn);
            NpgsqlDataReader dr = command.ExecuteReader();
            txtEditValue.Text = dr["center_Name"].ToString();
            conn.Close();
return "Select Success";
        }
        catch (Exception ex)
        {
            return "failure";
        }
}

这个错误告诉我 运行 项目

CS0120: An object reference is required for the non-static field, method, or property '_Default.txtEditValue'

给我一个新的一步一步的答案

您不能在 static 方法中访问表单元素,因为您的 form 是一个 class 并且此表单上的元素类似于此表单的 children 所以您不能直接在静态方法中访问 form elements。你可以做的是 WebMethod 中的 return value,你想在文本框中设置它并在 success of ajax 中设置值。

You are reading value from datareader after you have closed the connection. Datareader needs an open connection to read data you should close the connection after you have read the data from datareader. Also you have to call Read() method of datareader in order to get data.

[WebMethod]
public static string Edit(string dt1)
{
string pcId = dt1;
string strToReturn="";
NpgsqlConnection conn = new NpgsqlConnection("Server=192.168.0.133;User Id=123; " + "Password=123;Database=checDB;"); 
try
 {
   conn.Open(); 
   NpgsqlCommand command = new NpgsqlCommand("select Center_Id,center_Name from tbl_Profit_Centers where Center_Id = " + pcId, conn);
   NpgsqlDataReader dr = command.ExecuteReader();
   while(dr.Read())
   {
    strToReturn= dr["center_Name"].ToString();
   }
   conn.Close();
  }
catch (Exception ex)
  {
    strToReturn= "failure";
  }
    return strToReturn;

}

.ajax({
        type: "POST",
        url: "CS.aspx/Edit", 
        data: "{'dt1':'" + dt1 +"'}",
        contentType: "application/json; charset=utf-8",
        dataType:"json", 
        success: function(result)
         {
            $('input[id$=txtEditValue]').val(result.d);
         }
    });