Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winform Custom Control Why "Object Reference not set to an instance of an object"?

Tags:

c#

winforms

I created a custom control with a max value. When adding if (DesignMode) Parent.Refresh(); it compiles but in client it crashes with the message error:

Object Reference not set to an instance of an object

Call stack:

at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value)
at Microsoft.VisualStudio.Shell.Design.VsTargetFrameworkPropertyDescriptor.SetValue(Object component, Object value)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializePropertyAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement, CodePropertyReferenceExpression propertyReferenceEx, Boolean reportError)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeAssignStatement(IDesignerSerializationManager manager, CodeAssignStatement statement)
at System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeStatement(IDesignerSerializationManager manager, CodeStatement statement) 

Source code:

[Category("Main")]
[Description("Max Value")]
[DefaultValue(100)]
public int Max
{
    get { return _max; }
    set { 
        _max = value;
        if (DesignMode)
        {
            Parent.Refresh();
        }
    }
}
like image 566
user310291 Avatar asked Sep 15 '25 06:09

user310291


1 Answers

try this:

if (DesignMode && Parent != null)
{
    Parent.Refresh();
}

Most probably the control has not yet been added to its Parent when the value is set for the first time.

If you look at your Form's *.designer.cs, you'll notice that the properties of your usercontrol get assigned before it gets added to the parent form. That's why you get the exception.

like image 131
Botz3000 Avatar answered Sep 17 '25 01:09

Botz3000