You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Windows Form中FormatException未处理求助:文本框值≤100校验异常

Fixing FormatException in C# WinForms Textbox Validation (Value ≤100)

Hey there! Let’s tackle that FormatException you’re running into when validating your WinForms textbox. The root cause here is almost certainly that you’re trying to convert the text input to a numeric type (like int or double) without first checking if it’s actually a valid number—so when someone enters letters, symbols, or gibberish, that conversion fails hard with a FormatException.

Here’s a step-by-step solution to handle both validation and avoid that exception:

1. Use the Right Event for Validation

The Validating event is perfect for this job—it triggers when the textbox loses focus, and lets you block focus from moving away if the input is invalid. You can hook this up either via the Visual Studio designer (find the Validating event in the textbox’s properties window) or in code:

// Add this in your form's constructor or Load event
yourTextBoxName.Validating += YourTextBox_Validating;

2. Safe Conversion with TryParse

Instead of using int.Parse() (which throws exceptions on bad input), use int.TryParse()—it returns a boolean telling you if the conversion worked, and outputs the numeric value if it did. This eliminates the FormatException entirely.

Here’s the full event handler code:

private void YourTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
    TextBox inputBox = sender as TextBox;
    if (inputBox == null) return;

    // First, handle empty or whitespace-only input if needed
    if (string.IsNullOrWhiteSpace(inputBox.Text))
    {
        MessageBox.Show("Please enter a value!");
        e.Cancel = true; // Keep focus on the textbox
        inputBox.SelectAll(); // Highlight text for easy editing
        return;
    }

    // Try converting the input to an integer
    if (!int.TryParse(inputBox.Text, out int inputValue))
    {
        MessageBox.Show("Please enter a valid whole number!");
        e.Cancel = true;
        inputBox.SelectAll();
        return;
    }

    // Now check if the value exceeds 100
    if (inputValue > 100)
    {
        MessageBox.Show("Value cannot be greater than 100!");
        e.Cancel = true;
        inputBox.SelectAll();
    }
}

3. Adjust for Decimal Values (If Needed)

If your textbox should accept decimal numbers (like 99.5), swap int with double and use double.TryParse() instead:

if (!double.TryParse(inputBox.Text, out double inputValue))
{
    MessageBox.Show("Please enter a valid number!");
    // ... rest of the logic stays similar
}

Why This Works

  • TryParse safely handles non-numeric input without throwing exceptions, so you won’t get that FormatException anymore.
  • The Validating event ensures validation happens at the right time, and e.Cancel = true forces the user to fix the input before moving on.
  • Selecting all text makes it easy for users to correct their input without manually highlighting.

内容的提问来源于stack exchange,提问作者Libra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:39:22