views:

119

answers:

3

Hello All,

I have developed a User Control in Visual Studio (WinForms C#) and have a question.

I need the user of my User Control to be able to change certain string values and I would like them to be able to add the user control to their Form and click on it to bring up the Properties Pane where my User Control's custom properties will be displayed.

How can I have my own cutom properties for my user control? For example:

My user control contains a TextBox, and I would like the user to be able to change the value of that textbox via a property named "Text" or "Value" in the properties at Design-Time.

I'd really appreciate any help/suggestions at all.

Thank you. :)

Bael.

+4  A: 

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get { return myInnerTextBox.Text; }
  set { myInnerTextBox.Text = value; }
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

Nick Craver
Thank you very much @Nick. :)
baeltazor
+1  A: 

Just add public properties to the user control.

You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

Jason Williams
+3  A: 

It is very simple, just add a property:

public string Value {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}

Using the Text property is a bit trickier, the UserControl class intentionally hides it. You'll need to override the attributes:

[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public override string Text {
  get { return textBox1.Text; }
  set { textBox1.Text = value; }
}
Hans Passant