开发者

C# Why does the TextChanged event takes the previous width?

In my winforms application I have some code that needs to be executed after the text is changed. On the label I have a textchanged event with the following code:

string value = lblText.Text;
int labelWidth = lblText.Width;
int controlWidth = groupPanel1.Width;

int difference = c开发者_Go百科ontrolWidth - labelWidth;

lblText.Left = difference / 2;

When I set a breakpoint at string value = lblText.Text; I see the correct value. But the width property returns the width of the previous value of the text property.

For example:

The first time: text = "hello world!" width: 0

Second time: text = "h" width: 60

Third time: text = "hi" width: 13

How is that possible?


If that is a label with an autosize property on, then it will refit after the paint event. Looks like you are changing the text and asking for the new width, but not asking after the paint, so it still has the last width.


You should use something like this (your code moved to delegate):

private void label1_TextChanged(object sender, EventArgs e) {
    this.BeginInvoke(new Action(delegate {
        string value = lblText.Text;
        int labelWidth = lblText.Width;
        int controlWidth = groupPanel1.Width;
        int difference = controlWidth - labelWidth;
        lblText.Left = difference / 2;
                    this.Text = label1.Width.ToString();
    }));
}

Place this code to TextChanged handler.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜