need to change TextBox.Text inside TextChanged, something forces form close

Posted by Istrebitel on Stack Overflow See other posts from Stack Overflow or by Istrebitel
Published on 2012-04-14T11:33:50Z Indexed on 2012/04/14 23:29 UTC
Read the original article Hit count: 253

Filed under:
|
|

I am making a TextBox behave like if it could store a null value. In order to do that, i have a variable NullMode that indicates wether the value is stored is Null, and in TextChanged i set that to false, and on specific user action i set it to true and Text to a value that indicates that there is null inside the textbox. Then, based on NullMode, textbox is drawn differently.

Now, i have a semaphore-like approach in order to prevent event handle from firing when i dont need it. Here is how it looks:

                private void input_TextChanged(object sender, EventArgs e)
        {
            if (_preventTextBoxEvents) 
                return;

            _preventTextBoxEvents = true;

            //if (NullMode)
            //  Text = "";
            NullMode = false;
            ValidateInput();

            _preventTextBoxEvents = false;
        }

Now, if i need to set a textbox text to something that should show while in nullmode, i just set _preventTextBoxEvents before i do to true and it works all right.

BUT! I need to also remove the text when user tries to input something into the textbox! So i need to set Text to "". Problem is, if i uncomment that, form is closed after the event handler exits. I cannot prevent it (e.Cancel = true in FormClosing doesnt help!) and do not understand what can be causing it. There is no error message too (and i'm not doing try-catch).

My logic, when i do Text="". OnTextChanged should fire, it should call my TextChanged and it will see _preventTextBoxEvents is true and exit, so there would be no stack overflow / infinite recursion.

What is going on?

© Stack Overflow or respective owner

Related posts about c#

Related posts about winforms