9

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 "

3
  • Just gridToBind.DataSource = ds? And don't store your DateTime values as a character. Commented Jun 18, 2015 at 9:30
  • 1
    It is not working.Ok i will change that string params.My Concentration is to bind the gridview only.. Commented Jun 18, 2015 at 9:30
  • aspsnippets.com/Articles/… Commented Aug 7, 2015 at 7:07

6 Answers 6

11
+50

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That means 100 users who use the site will make use of same instance of static webmethod.i am correct?so the site performance will get affected or not?
Actually performance will be a bit better since there will be no need to create 100 instances. But this is a bit only.
how this webmethod works? first request process then second or simoultaneously?
Simultaneously processed therefore you may have synchronization issues with static methods. See here why normally you should avoid static methods in Asp.Net stackoverflow.com/questions/194999/…
3

if you are going to use static method then you will not be able to use any control of page , because they belong to a class of a page which does not have static scope. in static method you are only allowed to use static data,control etc. The possible solution is you will have to make a new instance of you parent class i.e. Page Class in static method and afterwards you can access all the control of page that instance. like this..

public static <ReturnType> MethodName { Class instance=new Class(); instance.GridView.DataSource=ds; instance.GridView.DataBind(); } 

but the given way does not work if want to retain data back, as the instnace will be new so old data will be flushed.

1 Comment

This will make a new instance of the form and the gridview of new instance will be populated. This will not populate the GridView on original form so this is not the right approach.
2

You can pass the reference of gridview to the static method and bind the girdview.

If you make a new instance of the class and call the static method it will create new form and all controls will be created for that specific instance so the gridview on original form will never be populated.

Here is an example how you can pass reference and bindgridview.

protected void Page_Load(object sender, EventArgs e) { GridView grd = grdTest; //grdTest is Id of gridview BindGrid(grd); } public static void BindGrid(GridView grd) { using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) { SqlCommand cmd = new SqlCommand("select* from testtable", con); SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); adapter.Fill(dt); grd.DataSource = dt; grd.DataBind(); } } 

2 Comments

i am calling public static DataTable GetDataTable() method inside a webmethod.. not from page_load.what all the changes required on your answer.
Than you need to return data and create html in success of ajax.
2

the problem is not with static keyword, it is with web method keyword,
when asp.net control post backs,
it took whole form on server hence form can get each control of your server.

while web method have only data that you pass through it parameters, it does not even know name of control available in your asp page

you have 2 option
either remove webmethod and let it post back or
create your gridview from jquery by table, tr, td
how ever i dont know about gridview passing in parameter of web method you can also check on it but i think you can read it only(if possible), binding is not possible

Comments

1

The problem you have it's related with how asp.net webforms does the data bindin to it's controls.

When you are in a normal postback and you populate the gridview datasource with some data, this data is "recorded" in the gridview viewstate and then is rendered in the browser in a hidden field named _VIEWSTATE and this is where you problem is.

When you do the ajax call and invoking your (static) web method your server controls do not exist because your not having the full page cycle.

What you can do is save your datasource in the Session for later handling.

In relation to your JQuery ajax call, you have to handle it manually, maybe using library like knockout or you can replace your current jquery ajax call for a hidden button where you would put your current code and put your gridview and this button inside an UpdatePanel and do a partial update.

Comments

1

You can do this way, Return datatable from static method.

public static DataTable GridData(string para1, string para2) { using (SqlConnection con = new SqlConnection(strconn)) { using (SqlCommand cmd = new SqlCommand()) { con.Open(); cmd.CommandText = "SP_Name"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@para1", para1); cmd.Parameters.AddWithValue("@para2", para2); cmd.Connection=con; SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); con.Close(); return dt; } } } [WebMethod] public static List<ClassName> BindGridData(string para1,string para2) { DataTable dt = ClassName.GridData(para1, para2); List<ClassName> list = new List<ClassName>(); foreach (DataRow dr in dt.Rows) { ClassName pa = new ClassName(); pa.para1 = Convert.ToString(dr["para1"]); pa.para2 = Convert.ToString(dr["para2"]); list.Add(pa); } return list; } 

And bind this web method to j query and Ajax.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.