C# Windows Form中FormatException未处理求助:文本框值≤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
TryParsesafely handles non-numeric input without throwing exceptions, so you won’t get that FormatException anymore.- The
Validatingevent ensures validation happens at the right time, ande.Cancel = trueforces 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

