How to Bind a gridview from a static WebMethod

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.


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.


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


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();
  }
}