简体   繁体   中英

C# Exception causes my form to close

When I throw a FormatException, the form always seems to close. Is there a way that the form doesn't close so I can do actions on the form?

Example:

    int postcodeNumeriek = 0;
    if (int.TryParse(postcode.Text, out postcodeNumeriek) == false)
    {
        throw new FormatException("De postcode heeft een verkeerd formaat");
    }

    cmd.Parameters.AddWithValue("@naam", familienaam.Text);
    cmd.Parameters.AddWithValue("@voornaam", voornaam.Text);
    cmd.Parameters.AddWithValue("@straat", straat.Text);
    cmd.Parameters.AddWithValue("@nummer", nummer.Text);
    cmd.Parameters.AddWithValue("@bus", bus.Text);
    cmd.Parameters.AddWithValue("@postcode", postcode.Text);
    cmd.Parameters.AddWithValue("@gemeente", gemeente.Text);
    cmd.Parameters.AddWithValue("@telefoonnummer", telefoonnummer.Text);
    cmd.Parameters.AddWithValue("@btwnummer", btwNummer.Text);
    cmd.Parameters.AddWithValue("@nieuwsbrief", nieuwsbrief.Checked);
    cmd.Parameters.AddWithValue("@emailadres", emailAdres.Text);
    cmd.Parameters.AddWithValue("@klantnummer", klantID);

    cmd.ExecuteNonQuery();

    cmd = new SqlCeCommand("UPDATE Klanten SET Actief=0 WHERE ID='" + recordID + "'", Klantenbeheer.HuidigeDatabaseVerbinding);
    cmd.ExecuteNonQuery();
}
catch (FormatException e)
{
    postcode.Focus();
}

In this example, I want my postal code to generate an exception when it is formatted incorrectly. When this happens, the form just closes so the postcode.Focus(); doesn't get executed.

Maybe it does but it's not visible.

Ik denk dat het handiger is als je die FormatException weg haalt. En de textbox bijvoorbeeld vult met wat tekst waar in staat dat het formaat niet klopt.

I think it would be better to remove the FormatException. The tryparse is fine. But just fill the textbox with some info.

int postcodeNumeriek = 0;

if (int.TryParse(postcode.Text, out postcodeNumeriek) == false)
{
    postcode.Text ="format postalcode incorrect";
}

and in these cases its always good to use the Try statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM