简体   繁体   中英

How do I call a method that is in the webpart class file, from a usercontrol in SharePoint 2007?

I've followed the instructions in this MSDN article: http://msdn.microsoft.com/en-us/library/dd206945.aspx

Is it possible to call a method that is in the myWebPart.cs file, from the MyUserControl.ascx file? I don't seem to have intellisense of the methods in the myWebPart.cs unless I do:

myWebpart mywbprt = new myWebpart();
mywbprt.myMethInWebPartcs();

However that gets the error, and does not compile:

Error   2   'myWebpart' is a 'namespace' but is used like a 'type'

The myWebPart.cs and MyUserControl.ascx share the same namespace, and I thought that would be enough to call the methods in myWebPart.cs in the usercontrol, but apparently not?

Am I missing some intricacy of SharePoint?

First of all, it looks like the namespace that myWebPart is in has the same name as the web part. You should change that. You will then probably not have the compile-time error.

You will have a runtime error. If this method you want to call interacts with the runtime state of the web part, then it should not be called from outside the web part, most likely.

More to the point, the user control needs to find and call on the particular instance of the web part that is currently active, not create a new instance, which will have nothing to do with the instance that was already running.

If the method is a static method (or if it should be), then this makes somewhat better sense, but I would argue that such a method does not belong inside the web part. It should be moved to a class library shared by the web part and by the user control.

I agree with what John says, and I'd like to add the following...

If your user control is contained within your web part, you should be able to use the Parent property and go up the hierarchy to find it. Another way of handing communication between the two would be to register for events from one to the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM