Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an initial value for a user control property?

I am creating a custom user control and I am wondering how do you set an initial value for a property during design time? I have a property called Alignment that has 4 enum values TopRight, TopLeft, BottomRight and BottomLeft. So, when a user drops the user control onto a Form, I want the initial value of the property to be always BottomRight. How can I do this?

like image 490
John_Sheares Avatar asked Oct 31 '10 19:10

John_Sheares


People also ask

Can we set default value in property C#?

You can assign the default value using the DefaultValueAttribute attribute, as shown below.

What is Property in user control?

User Control properties are used to set the values of a User Control from the parent page.


2 Answers

You should set the initial value in the constructor of your user control, or when you declare the backing variable for the property.

The DefaultValue attribute does not set the initial value. As noted in the documentation, you need to set the initial value in code; the designer will use the DefaultValue attribute to determine whether to generate code to set the property.

like image 182
Jeff Ogata Avatar answered Oct 25 '22 01:10

Jeff Ogata


Set Attributes for the property

[DefaultValue(typeof(AlignmentType), "BottomRight")]
public AlignmentType Alignment {

}

Edit: Actually, the above only helps the designer determine if it needs to otherwise specify the property in the initialization code.

With that in mind, you would simply either use your constructor to set the default value, or set the default value with the variable declaration.

like image 25
pinkfloydx33 Avatar answered Oct 25 '22 01:10

pinkfloydx33