maandag 11 april 2011

Passing data to a visual web part user control

In Visual Studio 2010 it's now possible to create a web part based on a ascx user control. This was of course also possible in SharePoint 2007 but you can now do it more quickly via the provided Visual Studio templates. In the web part code itself, the class inheriting from the webpart class, you can load the user control in two different ways:

1.
Control control = Page.LoadControl("pathToAscx"); Controls.Add(control) ;
2.
Control control = Page.LoadControl(typeof(nameOfYourAscxClass), object[]);
Controls.Add(control);

The first one just creates an instance of your user control passing no parameters to the constructor. Via the second one you can also pass parameters to the constructor. Number, order and type of these parameters must be the same as the those of the constructors. Now sometimes you want to add properties to your web part to let the user configure some options.

You could use the second LoadControl to pass these parameters to your user control but you can also take this approach:

1. Create properties in your UserControl class
2. Assign them before adding the control like this:
MyControl myControl = (MyControl)Page.LoadControl("pathToAscx");
myControl.property1 = "value1";
myControl.property2 = "value2";
Controls.Add(myControl);

1 opmerking:

  1. Hi,This is especially true if you have a good instructor who will be patient and take the time to start from the beginning as he teaches you how to use software for Web Design Cochin.Thanks....

    BeantwoordenVerwijderen