The Database Managers, Inc.

Contact The Database Managers, Inc.


Use an RSS enabled news reader to read these articles.Use an RSS enabled news reader to read these articles.

TEdit: Controlling userīs input

Date: Sun, 23 May 1999 12:05:13 +1200
(copied and edited from a message posted on borland.public.cppbuilder.language)

Q:  I want a TEdit that allows the user to enter a float value but doesn't let the user enter anything else.

A:  Try this:

void __fastcall TForm1::Edit1Change(TObject *Sender)
{
    static AnsiString lastvalid = "";
    if (Edit1->Text == "")
        return;
    try
    {
        Edit1->Text.ToDouble();
        lastvalid = Edit1->Text;
    }
    catch (...)
    {
        Edit1->Text = lastvalid;
    }
}

When this routine fires it tries to convert (using AnsiString::ToDouble(), although you could use StrToFloat() just as well) and if there's an error resets the text to the last known good value.  Empty strings aren't tested, etc.  I tried it out and the worst that happens is it calls itself again if an invalid number is entered.

BTW: if you are running this program from the compiler then it is most likely that you will still see the exceptions and it will break at the line containing the conversion, even though you've wrapped it in a try...catch statement.  This is normal behavior for debugging and you can just continue on as though it was a normal breakpoint.  Or if it really annoys you, you can turn off certain exceptions in the debugger options.  That way it won't drop back to the debugger every time the exception is thrown.  When not debugging (ie: running the program normally) you won't see exceptions that are caught by your program.

Corey Murtagh
The Electric Monk


Popular C++ topics at The Database Managers:

C++ FAQ Services | Programming | Contact Us | Recent Updates
Send feedback to: