I have called a Code behind method using jQuery using Static web Method. That web method call was success but when i bind grid view inside that method , gives an error that, we can not use control in static method.how can we solve this problem ?.
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];
}
And getting error " An object reference is required for the non-static field, method, or property "
You can not do what you want.
You are misunderstanding difference between static and instance. For example your page can be used by hundreds of different persons. Every person will be served different instance of your page and every person will see different instance of GridView. On the other hand,since your WebMethod is static, ALL of these hundreds of different persons will be served ONE method.
Then how can your static method decide which one to serve? It can't.
If you want to populate grid view from ajax, you need to send back data from your WebMethod, see one example here.
Read following article to learn more Why WebMethod are static.