Question

I have a "numeric textbox" in C# .NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type double? (or Nullable<double>). It's nullable to support the case where the user doesn't enter anything.

The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent():

this.numericTextBox1.Value = 1;

Remember 'Value' is of type Nullable<double>. This generates the following warning whenever I try to reopen the form in the Designer:

Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'.

As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying.

Any suggestions?

Was it helpful?

Solution

Or, if you don't want the designer adding any code at all... add this to the Property.

[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]

OTHER TIPS

It seems that there is an issue in Visual Studio 2008. You should create custom CodeDomSerializer to work around it:

public class CategoricalDataPointCodeDomSerializer : CodeDomSerializer
{
    public override object Deserialize(IDesignerSerializationManager manager, object codeObject)
    {
        CodeStatementCollection collection = codeObject as CodeStatementCollection;

        if (collection != null)
        {
            foreach (CodeStatement statement in collection)
            {
                CodeAssignStatement codeAssignment = statement as CodeAssignStatement;

                if (codeAssignment != null)
                {
                    CodePropertyReferenceExpression properyRef = codeAssignment.Left as CodePropertyReferenceExpression;
                    CodePrimitiveExpression primitiveExpression = codeAssignment.Right as CodePrimitiveExpression;

                    if (properyRef != null && properyRef.PropertyName == "Value" && primitiveExpression != null && primitiveExpression.Value != null)
                    {
                        primitiveExpression.Value = Convert.ToDouble(primitiveExpression.Value);
                        break;
                    }
                }
            }
        }

        return base.Deserialize(manager, codeObject);
    }
}

Then you should apply it by using the DesignerSerializer attribute on your class.

Could it help to setting the DefaultValue attribute on that property to new Nullable(1)?

[DefaultValue(new Nullable<double>(1))]  
public double? Value ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top