Ath*_*hul 8 .net c# asp.net static-methods datagridview
我使用静态Web方法使用jQuery调用了一个代码隐藏方法.那个web方法调用是成功的,但是当我在该方法中绑定网格视图时会产生一个错误,该错误无法在静态方法中使用控件.我们可以解决这个问题.
public static DataTable GetDataTable()
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand("StoredProcedurename");
String constr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
string Startdate = DateTime.Now.ToString("yyyy-MM-dd");
string EndDate = Convert.ToDateTime(Startdate).AddMonths(-6).ToString("yyyy-MM-dd");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FromDate", Startdate);
cmd.Parameters.AddWithValue("@ToDate", EndDate );
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds);
//i want to use same dataset to bind with the grid
gridToBind.DataSource = ds.Tables[1];
gridToBind.DataBind();
txtStatus.Text="Data Received";
//above three lines throws error.
return ds.Tables[1];
}
Run Code Online (Sandbox Code Playgroud)
并获得错误"非静态字段,方法或属性需要对象引用"
你无法做你想做的事.
你误解了静态和实例之间的区别.例如,您的页面可以被数百个不同的人使用.每个人都将为您的页面提供不同的实例,每个人都会看到不同的GridView实例.另一方面,由于您的WebMethod是静态的,所以这些数百个不同的人将被提供一种方法.
那么你的静态方法如何决定服务哪个?它不能.
如果要从ajax填充网格视图,则需要从WebMethod发回数据,请参阅此处的一个示例.
阅读以下文章以了解更多信息为什么WebMethod是静态的.