tags:

views:

103

answers:

2

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 = controlWidth - 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?

+4  A: 

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.

gbianchi
So basically what you are saying is, the text property is changed but the label isn't redrawn yet and that's why I have the width of the previous value?
Martijn
yes, you need to check the value after you paint it again. You changed the text value, that will raise a re paint event for the label, but until it execute, it will remain the same.
gbianchi
So I need to invoke Invalidate() on the label? And after that I can get the right width?
Martijn
Yes, Invalidate, Refresh, or whatever function that make a re paint to the control....
gbianchi
Thnx, that did the trick :)
Martijn
A: 

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.

Andrey Shvydky
why didn't you just use lambda? its easier to read.
Stan R.
I'm sorry. I'm just a junior programmer, I don't understand this code completely. Where do I put this code? How do I use it?
Martijn
Martijn, I have changed my code to show you all event handler body.
Andrey Shvydky