Visual Studio 2010 has a new template allowing you to create Visual Web Parts. One advantage of Visual Web Part as opposed to a regular web part is the ability to add user controls and markup of the web part right in the visual mode without having to provision it in your code-behind file.
If you developed web parts before, you know that hardly ever your web part will not need to accept properties. Usually the whole purpose of creating one is to allow your users or administrators to customize the properties.
When you create a new Visual WebPart (say call it SampleWP), among other files you will see the following key files:
1. SampleWP.CS
2. SampleWPUserControl.ascx
3. SampleWPUserControl.ascx.cs
In traditional web part you would define your properties in the file that inherits from WebPart class. In our case it’s SampleWP.CS. However, your entire logic is happening in your user control code behind file and therefore you need to reference web part properties in there.
Here is how to define properties that will be used in your code user control behind file.
1. In your SampleWP.CS set the following value of class identifier [ToolboxItemAttribute(true)]
2. In your class define the property that will be displayed to a user:
If you developed web parts before, you know that hardly ever your web part will not need to accept properties. Usually the whole purpose of creating one is to allow your users or administrators to customize the properties.
When you create a new Visual WebPart (say call it SampleWP), among other files you will see the following key files:
1. SampleWP.CS
2. SampleWPUserControl.ascx
3. SampleWPUserControl.ascx.cs
In traditional web part you would define your properties in the file that inherits from WebPart class. In our case it’s SampleWP.CS. However, your entire logic is happening in your user control code behind file and therefore you need to reference web part properties in there.
Here is how to define properties that will be used in your code user control behind file.
1. In your SampleWP.CS set the following value of class identifier [ToolboxItemAttribute(true)]
2. In your class define the property that will be displayed to a user:
[WebBrowsable(true),Category("Configuration"),Personalizable(PersonalizationScope.Shared),DefaultValue(""),WebDisplayName("Property Title"),WebDescription("Property Description")]public string MyProperty{get { return myprop; }set { myprop = value; }}public static string myprop;
Above, the ‘myprop’ static variable is the variable that will be referenced in your user control code behind class. like this:
someLabelOnForm.Text = SampleWP.myprop;
As you can see we can assign the value of our property from SampleWP.CS that will be collected from a user to be used in our user control.
No comments:
Post a Comment