开发者

Cannot change the Label text!

I have created a custom control and added a label property to it so at design time we can pick a Label and assign it to that control. so basically I want that if a label is assigned to that control, its text should change as below and also its text should change to bold font, so here is that code:

private Label assignedLabel;
public Label AssignedLabel
{
    get
    {
        return assignedLabel;
    }
    set
    {
        assignedLabel = value;
        assignedLabel.Text =开发者_如何学Python @"*" + assignedLabel.Text; 
        assignedLabel.Font = new Font(AssignedLabel.Font, FontStyle.Bold);
        AssignedLabel.Refresh();
    }
}

the problem is that based on the code above the Font of that assigned label is correctly changing to Bold font, but its Text is not taking affect. why is that happening? how can I fix this issue?


I don't think you can do that unless it is set in the InitializeComponent() subroutine for the control.

Actually, is the font being set to a default before you change it?


It really sounds like you should explore DataBinding. This is perfect for handling the internals of updating a label based on some other control's state.

For example, if you have two controls, a TextBox (textBox1) and a Label (label1), you could call the following line of code whenever you want to bind them:

label1.DataBindings.Add("Text", textBox1, "Text");

This binds the "Text" property of label1 to the "Text" property of the textBox1 object. You can use any object here. The "correct" way to do it would be to create an underlying data source that contains the current state of many variables, and bind all controls to that data source. But this type of code will get you going quickly.


Hmmm! the code just started working! there is a minor issue that it is adding "*" every time I run the form, but it should be an easy fix. any other nice ways to accomplish this goal are welcome :) thanks all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜