Martijn
Martijn

Reputation: 24809

C# How to set the default value of an object in the propertygrid?

I have an object which inherits from Button. This button is a property of an object which inherit from TableLayoutPanel. The property is called MyButton:

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
**[DefaultValue(??? Something Like Visible = false ???)]**
public CustomButton MyButton
{
    get { return _button; }
    set { _button = value; }
}

Now, in the designer, I want to set the Visible property of MyButton to be false. Default the Visible property true, but in this case, I want it to be false.

How can I do this?

Upvotes: 2

Views: 3293

Answers (4)

cfeduke
cfeduke

Reputation: 23236

Because your value is not a constant value it cannot be used with DefaultValueAttribute since these values are required at compile time. Instead you can disregard DefaultValueAttribute and in the constructor you can initialize the MyButton attribute with a custom instance of CustomButton with the default attributes set on it. The only irregularity here is that in the property grid the property value will appear bold as if the user had changed it.

Here is an example:

public YourCustomControlClass()
{
    this.MyButton = new CustomButton { Visible = false; };
}

Upvotes: 1

Bolu
Bolu

Reputation: 8786

in your MyButton Class, remove anything you've added trying to override the Visible property add following code:

public MyButton()
{
    this.Visible=false;
}

Rebuild it, then add a new Mybutton instance to your form, you can see its visible property in the Designer is set to False now.

Upvotes: 1

ShahidAzim
ShahidAzim

Reputation: 1494

Override the property and then set the default value:

[DefaultValue(false)]
new public bool Visible
{
  get { return base.Visible; }
  set { base.Visible = value; }
} 

Hope this will work.

Upvotes: 0

Related Questions