Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set an enum value to a custom property of a web user control?

How do we bind an enum value to the property of a web user control? I keep receiving this error.

Cannot create an object of type 'MyEnum' from its string representation 'MyEnum.MyValue' for the 'MyProperty' property.

This is the code behind MyWebUserControl.ascx.cs

[System.ComponentModel.Bindable(true)]
public MyEnum MyProperty { get; set; }

SomeWebUserControl.ascx

<!-- This fails -->
<uc1:MyWebUserControl runat="server" ID="MyControl1"
    MyProperty="MyEnum.MyValue" />

<!-- This fails -->
<uc1:MyWebUserControl runat="server" ID="MyControl2" 
    MyProperty="<%# MyEnum.MyValue %>" />

<!-- This works -->
<uc1:MyWebUserControl runat="server" ID="MyControl3"
    MyProperty="0" />
like image 954
Shaun Luttin Avatar asked Oct 24 '25 06:10

Shaun Luttin


1 Answers

Defining the property on the control is easy, as you have done:

[System.ComponentModel.Bindable(true)]
public MyEnum MyProperty { get; set; }

However, it's worth noting that the [Bindable(true)] attribute isn't needed. It's just there as a hint for VS to offer additional databinding properties in the property grid. It doesn't affect the ASP.NET runtime at all.

To set this property statically in the ASPX markup, just use the enum's value:

<uc1:MyWebUserControl runat="server"
    ID="MyControl1"
    MyProperty="MyValue" />

If you want to set it dynamically, you can do it in Page_Init:

void Page_Init() {
    MyControl1.MyProperty = GetEnumValueFromSomewhere();
}

<uc1:MyWebUserControl runat="server"
    ID="MyControl1" />

And finally, to set it dynamically as part of databinding, you can use the <%# foo %> databinding syntax:

<uc1:MyWebUserControl runat="server"
    ID="MyControl1"
    MyProperty="<%# GetEnumValueFromSomewhere() %>" />

Note that the databinding option should be used only when databinding. If you're not trying to do databinding, it is rather wasteful to call DataBind() on the entire page, or even just on that one control.

like image 168
Eilon Avatar answered Oct 25 '25 18:10

Eilon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!