I got this code in a user control:
[DefaultValue(typeof(Color), "Red")]
public Color MyColor { get; set; }
How can I change MyColor
to be its default value?
You can assign the default value using the DefaultValueAttribute attribute, as shown below.
Set a default valueIn the Navigation Pane, right-click the form that you want to change, and then click Design View. Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value.
A member's default value is typically its initial value. From this, you may conclude that if you set the DefaultValue attribute for a property, the property is initialized to that value. However, you should set the property's DefaultValue attribute equal to its initialized value.
In EF core released 27th June 2016 you can use fluent API for setting default value. Go to ApplicationDbContext class, find/create the method name OnModelCreating and add the following fluent API.
The DefaultValueAttribute
does not set the property to the value, it is purely informational. The Visual Studio designer will display this value as non-bold and other values as bold (changed), but you'll still have to set the property to the value in the constructor.
The designer will generate code for the property if the value was set by the user, but you can remove that code by right clicking on the property and clicking Reset
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With