How to Bind a gridview from a static WebMethod

21,375

Solution 1

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.

Solution 2

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.

Solution 3

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

Solution 4

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

Solution 5

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.

Share:
21,375
AcAnanth
Author by

AcAnanth

.net Developer.

Updated on July 22, 2022

Comments

  • AcAnanth
    AcAnanth almost 2 years

    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 "

    • Soner Gönül
      Soner Gönül almost 9 years
      Just gridToBind.DataSource = ds? And don't store your DateTime values as a character.
    • AcAnanth
      AcAnanth almost 9 years
      It is not working.Ok i will change that string params.My Concentration is to bind the gridview only..
    • Jitendra Pancholi
      Jitendra Pancholi almost 9 years
  • Mairaj Ahmad
    Mairaj Ahmad almost 9 years
    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.
  • AcAnanth
    AcAnanth almost 9 years
    i am calling public static DataTable GetDataTable() method inside a webmethod.. not from page_load.what all the changes required on your answer.
  • Mairaj Ahmad
    Mairaj Ahmad almost 9 years
    Than you need to return data and create html in success of ajax.
  • Admin
    Admin almost 9 years
    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?
  • Atilla Ozgur
    Atilla Ozgur almost 9 years
    Actually performance will be a bit better since there will be no need to create 100 instances. But this is a bit only.
  • Admin
    Admin almost 9 years
    how this webmethod works? first request process then second or simoultaneously?
  • Atilla Ozgur
    Atilla Ozgur almost 9 years
    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/…
  • Jitendra Pancholi
    Jitendra Pancholi almost 9 years