Reputation: 325
I am going to design a userControl which contains a textbox and a label.
How can I set a public property for label text?
this is my code:
public partial class CurrencyTextBoxWithLable : UserControl
{
public CurrencyTextBoxWithLable()
{
InitializeComponent();
}
private string _lblText;
public string LabelText
{
get
{
return _lblText;
}
set
{
_lblText = value;
}
}
}
But it doesn't work... Any help will be appreciated.
DesignerCode:
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 6);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 0;
this.label1.Text = this.LabelText;//Oooppsss!
}
Upvotes: 1
Views: 4626
Reputation: 6557
It's not working because you are overwriting your value from properties. In designer file you are calling this:
this.label1.Text = this.LabelText;
Looking at your getter, it's returning _lblText
value:
get
{
return _lblText;
}
Since it's not initialized the value of _lblText
is empty string (""). Try setting value of _lblText
to some initial value and run your code again. For example add this:
private string _lblText = "Label1";
EDIT:
When you add label to your form it looks like this:
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(46, 17);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
So, "label1" is the same value as in properties. When you change it in properties, to lets say Test label string
, designer will have value of:
this.label1.Test = "Test label string";
Try removing and adding your label again if it's not working for you. You should be able to change it's value through properties again.
Upvotes: 1