文本框输入校验求助:整数存储字符串判断及非数字输入检测
Hey there! Let's tackle your two input validation questions step by step—they’re both common hurdles when dealing with numeric text fields, so I’ve got you covered.
1. How to check if an integer-only text box has string input
For a text box that should only accept integers, the most reliable way is to use int.TryParse(). This method attempts to convert the input string to an integer, and returns false if the conversion fails (whether the input is a non-numeric string like "abc", a decimal like "12.3", or any other invalid format).
Here’s a quick example of how to use it:
string input = txtInteger.Text; if (int.TryParse(input, out int result)) { // Input is a valid integer—use 'result' here } else { // Input is not a valid integer (could be a string, decimal, etc.) MessageBox.Show("Please enter a whole number!"); txtInteger.Focus(); }
This avoids messy string checks (like manually looking for non-digit characters) because TryParse handles edge cases automatically (e.g., leading/trailing spaces are allowed by default, but you can adjust that with NumberStyles if needed).
2. Validation for your Price (Double) text box
Let’s break down your issues here: first, the error with !string.IsNullOrWhiteSpace(), then validating numeric input, and finally updating the total.
First, if !string.IsNullOrWhiteSpace(txtAddItem.Text) is throwing an error, double-check that txtAddItem is properly linked to your text box control (in WinForms/WPF, this usually means the control’s Name property matches the variable name in your code, and the designer hasn’t lost the reference).
Now, for the full validation flow tailored to your scenario:
- Check for empty/whitespace input first.
- Validate that the input is a valid double (or better yet,
decimal—more on that below). - Update the total if validation passes.
Here’s a complete example of the button click event:
private void btnAddToTotal_Click(object sender, EventArgs e) { // Step 1: Check for empty input if (string.IsNullOrWhiteSpace(txtAddItem.Text)) { MessageBox.Show("Please enter a price before adding!"); txtAddItem.Focus(); return; } // Step 2: Validate numeric input (using double.TryParse) // Use InvariantCulture to avoid issues with decimal separators (e.g., . vs ,) if (!double.TryParse(txtAddItem.Text, System.Globalization.NumberStyles.Currency, System.Globalization.CultureInfo.InvariantCulture, out double inputPrice)) { MessageBox.Show("Please enter a valid number for the price!"); txtAddItem.SelectAll(); // Highlight invalid input for easy correction txtAddItem.Focus(); return; } // Step 3: Update the total double currentTotal = 0; // Parse the existing total (in case it's empty or invalid) double.TryParse(txtTotal.Text, out currentTotal); currentTotal += inputPrice; // Format the total to 2 decimal places for currency txtTotal.Text = currentTotal.ToString("F2"); // Clear the input box for next entry txtAddItem.Clear(); }
A quick note on double vs decimal for prices
If this is for currency, I’d recommend using decimal instead of double—doubles have floating-point precision issues (e.g., 0.1 + 0.2 doesn’t equal 0.3 exactly), which can cause incorrect totals over time. Switching to decimal.TryParse and decimal variables would fix that.
内容的提问来源于stack exchange,提问作者Lewis Mitchell

