Thursday, August 5, 2010

Getting the SPWeb object dynamically in WebParts

Hi All,
I have been working on some sharepoint webparts these days and found some queeky thing which people do regularly which I have listed below and even provided the resolution for it.
Generally, people get adhere to hardcode the URL's of different portals in the webparts which is quite a wrong thing. Instead we could do get the URL of the Site dynamically.

Wrong Approach:
***************************
public void RenderControls()/RenderContents(){
SPSite siteColl = new SPSite(":">http://:/");
SPWeb webSite = siteColl.OpenWeb();
.........
.......
}
***************************


Right Approach:
***************************
public void RenderControls()/RenderContents(){
//SPSite siteColl = SPContext.Current.Web.Site;
//SPWeb web = siteColl.RootWeb;
SPWeb web = SPContext.Current.Web;
..................
................
}
***************************

If you follow this process you wouldnt be in trouble if you add the same webpart in different portals across sites. It would work as dynamic one.

No comments:

Post a Comment