It is necessary to change TextBox.Text inside TextChanged, something reinforces the closing form

I am doing a TextBox as if it could store a null value. To do this, I have a NullMode variable that indicates that the value is stored in Null, and in TextChanged I am set to false, and for a specific user action I set true and Text to a value indicating that null exists inside the text field. Then, based on NullMode, the text box is drawn differently.

Now I have a semaphop-like approach to prevent the event descriptor from triggering when I don't need it. Here's what it looks like:

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

            _preventTextBoxEvents = true;

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

            _preventTextBoxEvents = false;
        }

, -, nullmode, _preventTextBoxEvents, true, .

! , - ! Text "". , , . (e.Cancel = true FormClosing !) , . ( try-catch).

, Text = "". OnTextChanged , TextChanged, , _preventTextBoxEvents , / .

?

+3
1

( input)

if (NullMode) 
    input.Text = ""; 

, input.Text.
, . - ValidateInput , , _preventTextBoxEvents false;

-

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

        _preventTextBoxEvents = true;   
        try
        {
           if (NullMode) input.Text = "";   
           NullMode = false;   
           ValidateInput();   
        }
        catch(Exception ex)
        {
            // Inform user of the exception occurred inside your ValidateInput
            MessageBox.Show(ex.Message);
        }
        finally
        {
            // Be sure to restore this global to a functioning value.
            _preventTextBoxEvents = false;   
        }
    }   

, _preventTextBoxEvents, TextChanged, :

try
{
    input.TextChanged -= new EventArgs(input_TextChanged);
    // Now, the input textbox is no more connected to this code, you 
    // could happily change the textbox text without worry to reenter in this code
}
...
finally
{
    // Work finished, reconnect this code to the event TextChanged
    input.TextChanged += new EventArgs(input_TextChanged);
}
+3

All Articles