views:

56

answers:

3

I saw 2 different way to create web parts for sharepoint. Which one is preferred by most?

http://msdn.microsoft.com/en-us/library/aa973249%28office.12%29.aspx

A: 

Both SharepointOverflow and Stackoverflow aren't much help. Used to be really good. I followed this link and I guess I am happy with the result.

http://msdn.microsoft.com/en-us/library/ms415817(office.12).aspx

Bob Dinero
I CAN NOT BELIEVE SOMEONE HAD GUT TO PUT NEGATIVE REMARK ON USEFUL STATUS. OFF COURSE IT'S USEFUL. I EVEN PUT A LINK SO THAT IN FUTURE OTHERS CAN FOLLOW IT. CHICKEN...
Bob Dinero
A: 

For the few web parts I've written, I guess I've gone more with method #2 than method #1. Seems more straightforward and has the potential to be reused outside of the SharePoint environment (depending on the depth of your business logic).

Jesse C. Slicer
Thanks Jesse for your input. I know what you mean about using the second method. Web part are based on asp.net (2.0), therefore it's more useful beyond sharepoint application. Thanks for your words.
Bob Dinero
+1  A: 

Anything involving VSeWSS is just going to end in pain, so method 1 is definitely out. Method 2 isn't ideal either, as setting up html elements as controls becomes unmanageable at a level just beyond what you see in that demo. I use a fairly simple generic base class that takes a user control as a type parameter and lets me keep all the layout nicely seperated from the sharepoint infrastructure. If you are creating pages/web parts programatically most of the web part xml turns out to be optional also.

public abstract class UserControlWebPart<T> : Microsoft.SharePoint.WebPartPages.WebPart where T:UserControl
{
    protected UserControlWebPart()
    {
        this.ExportMode = WebPartExportMode.All;
    }

    protected virtual void TransferProperties(T ctrl)
    {
        var tc = typeof(T);
        var tt = this.GetType();

        foreach (var p in tt.GetProperties()) {
            if (p.IsDefined(typeof(ControlPropertyAttribute), true)) {
                foreach (var p2 in tc.GetProperties()) {
                    if (p2.Name == p.Name) {
                        p2.SetValue(ctrl, p.GetValue(this, null), null);
                    }
                }
            }
        }
   }


    protected override void CreateChildControls()
    {
        string controlURL = ControlFolder+typeof(T).Name+".ascx";
        var ctrl = Page.LoadControl(controlURL) as T;
        TransferProperties(ctrl);
        this.Controls.Add(ctrl);
    }

    protected virtual string ControlFolder
    {
        get {
            return "~/_layouts/UserControlWebParts/";
        }
    }

}
Tom Clarkson
Thanks Tom. This looks better and I truly appreciate the inside story of each uses. Great Job. Again. Thanks a Lot.
Bob Dinero