views:

133

answers:

2

Edit: It looks like it might be a Visual Studio issue. If I restart Visual Studio it works until I rebuild the solution.

I'm getting an "'B' could not be set on property 'MyMode'" exception in the designer when using this code:

public class MyControl : CompositeControl
{
  public enum MyEnum{ A, B }

  [DefaultValue(MyEnum.A)]
  public MyEnum MyMode
  {
    get
    {
      object obj = ViewState["MyMode"];
      return obj == null ? MyMode.A : (MyEnum)obj;
    }

    set
    {
      ViewState["MyMode"] = value;
    }
  }
}

To reproduce: Create the control in a project. Drag the control onto a web form in another project. Set MyMode = B in the properties window. Close the form, reopen the designer.

What am I doing wrong? Do I need to manually parse the string into an enum?

Edit: Designer generated code.

<cc1:MyControl ID="MyControl1" runat="server" MyMode="B"  />

Edit: In fact, this property also fails:

  public MyEnum MyMode
  {
    get
    {
      return MyEnum.A;
    }    
    set{}
  }
A: 

You're trying to set the value to 'B' which is a string. You need to set it to a numeric value, since that's what enums are....

...
set
{
  ViewState["MyMode"] = value; // <-- 'value' must be an integer equivalent to B
  // in this example, to set as 'B', 'value' == 1
}
...

EDIT see this article

Jason
Good idea about the int situation. Setting `ViewState["MyMode"] = 1`, just as a test, does not get rid of the error though.
Greg
A: 

This is a Visual Studio 2008 SP1 bug

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361826

Please note that there are actually two hotfixes released, as described on: http://support.microsoft.com/kb/961847

One is for Windows XP and 2009, while the other is for Windows Vista and Windows Server 2008.

Windows XP and 2003: http://support.microsoft.com/kb/969612/

Windows Vista and Windows Server 2008: http://support.microsoft.com/kb/967535/

Greg