JohnChris JohnChris - 2 months ago 9
C# Question

Textbox error catching message box display delay

I have a textbox, which does a math calculation and I don't want it to handle decimal points so I use int as the type and I add an error catch exception which displays a message box. I want the message box to have a delay timer on it so people can have time to change the value as the calculation occurs with a MouseMove event.

catch (FormatException fEX)
{
Message.Box("Value must be a divisisable by 1 exactly")


And no I don't want to use any thing like

(x % 1) == 0 just want a delay timer on the message box above

Answer

Use a Timer. In your catch, do not do the error message, instead, create a Timer object. Add to that timer's elapsed event a handler that will display the message only if the value is still invalid.

catch (FormatException fEX)
{
    if (MyFormatExcTimer == null) {
        MyFormatExcTimer = new Timer(1000);
        MyFormatExcTimer.elapsed += async ( sender, e ) => await HandleTimer();
        MyFormatExcTimer.start();
    }
}

private static Task HandleTimer()
{
    if (... format is still bad ...)
    {
        Message.Box("Value must be a divisisable by 1 exactly");
    } else {
        MyFormatExcTimer.Stop();
    }
    MyFormatExcTimer.Dispose();
    MyFormatExcTimer = null;
}

This is not very complete. You may need to create or dispose or start or stop the timer at different events, but without seeing more of your code it is hard to tell. I might actually not have the program fire off an exception on bad input, but accept any input and have my own code that tests it. My code would get fired off on any text changed event and could set off the timer if the input is bad or stop it if the input is ok. Also, you might consider not even firing off any messages during input, but rather firing verifying the data when the user tries to save it... but that assumes you have a "save" button or something like that, which you may not.