How to Bind a gridview from a static WebMethod

22.5k views Asked by At

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 "

6

There are 6 answers

5
Atilla Ozgur On BEST ANSWER

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.

1
hdkhardik On

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.

2
Mairaj Ahmad On

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

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

0
Musakkhir Sayyed On

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.

0
Coastpear On

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.