Click here to Skip to main content
14,926,224 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

My problem is that I am using the shown below code:

XML
<System.Web.Services.WebMethod()> _
    Public Shared Function GetCurrentTime()

...
C#
    GridView1.DataSource = SqlDataSource1
    GridView1.DataBind()


End Function


I am getting the error:

C#
Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.


Please help me fix this problem. Forum members, don't just tell the problem with the code but also post a relevant code that can fix the problem.

Thanks in Advance.

What I have tried:

VB.NET
Public Shared Function GetCurrentTime()

...
C#
    GridView1.DataSource = SqlDataSource1
    GridView1.DataBind()


End Function
Posted
Updated 11-Dec-16 23:19pm

You can't access instance members from within Shared methods: that is the whole point of Shared - it declares a method that operates without an instance being needed or even ever created. Shared methods do not have any access to a Me object reference.

If you want to access controls (or other non-shared objects in your class) the method cannot be Shared - it must be a normal instance method.
   
That's not your real problem, your real problem is that you're trying to access server controls via a webmethod. When you do a form postback you send a lot of data to the server and it goes through the asp.net page lifecycle. This allows asp.net to re-create the state of your controls and to update them, and that updated state is then converted into html to be shown in the browser. When you call a web method the only data sent is the data in the parameters, so .net can't recreate the controls, it doesn't run the whole page lifecycyle, and as the web method doesn't result in the whole page being re-endererd you can't update the controls in your web method either.

For what you want to do you should look at the UpdatePanel as that is a component designed to facilitate what you're trying to do, ie update the controls via ajax.
   
Comments
ZohaibRazaTheDProgrammer 12-Dec-16 5:28am
   
Thank you for clarifying. I am new to ASP .NET and Javascript. Can you please help me with a sample code?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900