9

入力検証が必要なフォームベースのプログラムを作成しました。ユーザーがテキストボックスの距離内にのみ数値を入力できるようにする必要があります。

これまでのところ、テキストボックスに何かが含まれていることを確認しましたが、値が含まれている場合は、入力された値が数値であることを検証する必要があります。

else if (txtEvDistance.Text.Length == 0)
        {
            MessageBox.Show("Please enter the distance");
        }
else if (cboAddEvent.Text //is numeric)
        {
            MessageBox.Show("Please enter a valid numeric distance");
        }
4

12 に答える 12

17

文字列を整数に解析し、操作の成功または失敗を示すブール値の結果を返すことができるTryParseメソッドを試すことができます。

int distance;
if (int.TryParse(txtEvDistance.Text, out distance))
{
    // it's a valid integer => you could use the distance variable here
}
于 2012-05-01T17:31:01.533 に答える
6

ここに別の簡単な解決策があります

try
{
    int temp=Convert.ToInt32(txtEvDistance.Text);
}
catch(Exception h)
{
    MessageBox.Show("Please provide number only");
}
于 2012-05-01T17:33:07.897 に答える
6

ユーザーが TextBox に情報を入力するときに数値以外の値を入力できないようにする場合は、次のようにイベント OnKeyPress を使用できます。

private void txtAditionalBatch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar)) e.Handled = true;         //Just Digits
            if (e.KeyChar == (char)8) e.Handled = false;            //Allow Backspace
            if (e.KeyChar == (char)13) btnSearch_Click(sender, e);  //Allow Enter            
        }

ユーザーがマウス (右クリック/貼り付け) を使用して TextBox に情報を貼り付けた場合、このソリューションは機能しません。その場合は、追加の検証を追加する必要があります。

于 2012-05-01T17:54:54.107 に答える
4

クライアント側でJavaScriptを使用するか、テキストボックスで正規表現バリデーターを使用して実行できます。

Javascript

script type="text/javascript" language="javascript">
    function validateNumbersOnly(e) {
        var unicode = e.charCode ? e.charCode : e.keyCode;
        if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
            return true;
        }
        else {

            window.alert("This field accepts only Numbers");
            return false;
        }
    }
</script>

Textbox (ValidationExpression 固定)

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator> 
于 2012-05-01T17:35:30.827 に答える
2

Int.TryParse に同意しますが、代わりに Regex を使用できます。

 Regex nonNumericRegex = new Regex(@"\D");
 if (nonNumericRegex.IsMatch(txtEvDistance.Text))
 {
   //Contains non numeric characters.
   return false;
 }
于 2014-01-02T11:57:55.423 に答える
2

あなたはこのようにすることができます

   // Check if the point entered is numeric or not
   if (Int32.TryParse(txtEvDistance.Text, out var outParse))
    {
       // Do what you want to do if numeric
    }
   else
    {
       // Do what you want to do if not numeric
    }     
于 2014-01-02T11:47:57.703 に答える
1

これは、マイナス記号付きの数値のみ、またはマイナス記号と小数点付きの小数のいずれかを許可するソリューションです。以前の回答のほとんどは、選択したテキストを考慮していませんでした。テキストボックスの ShortcutsEnabled を false に変更すると、ゴミをテキストボックスに貼り付けることもできなくなります (右クリックが無効になります)。一部のソリューションでは、マイナスの前にデータを入力できました。すべてをキャッチしたことを確認してください。

        private bool DecimalOnly_KeyPress(TextBox txt, bool numeric, KeyPressEventArgs e)
        {
            if (numeric)
            {
                // Test first character - either text is blank or the selection starts at first character.
                if (txt.Text == "" || txt.SelectionStart == 0)
                {
                    // If the first character is a minus or digit, AND
                    // if the text does not contain a minus OR the selected text DOES contain a minus.
                    if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
                        return false;
                    else
                        return true;
                }
                else
                {
                    // If it's not the first character, then it must be a digit or backspace
                    if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back))
                        return false;
                    else
                        return true;
                }
            }
            else
            {
                // Test first character - either text is blank or the selection starts at first character.
                if (txt.Text == "" || txt.SelectionStart == 0)
                {
                    // If the first character is a minus or digit, AND
                    // if the text does not contain a minus OR the selected text DOES contain a minus.
                    if ((e.KeyChar == '-' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains("-") || txt.SelectedText.Contains("-")))
                        return false;
                    else
                    {
                        // If the first character is a decimal point or digit, AND
                        // if the text does not contain a decimal point OR the selected text DOES contain a decimal point.
                        if ((e.KeyChar == '.' || char.IsDigit(e.KeyChar)) && (!txt.Text.Contains(".") || txt.SelectedText.Contains(".")))
                            return false;
                        else
                            return true;
                    }
                }
                else
                {
                    // If it's not the first character, then it must be a digit or backspace OR
                    // a decimal point AND
                    // if the text does not contain a decimal point or the selected text does contain a decimal point.
                    if (char.IsDigit(e.KeyChar) || e.KeyChar == Convert.ToChar(Keys.Back) || (e.KeyChar == '.' && (!txt.Text.Contains(".") || txt.SelectedText.Contains("."))))
                        return false;
                    else
                        return true;
                }

            }
        }
于 2014-12-13T15:15:55.860 に答える
1
        if (int.TryParse(txtDepartmentNo.Text, out checkNumber) == false)
        {
            lblMessage.Text = string.Empty;
            lblMessage.Visible = true;
            lblMessage.ForeColor = Color.Maroon;
            lblMessage.Text = "You have not entered a number";
            return;
        }
于 2014-01-28T15:26:45.220 に答える
1

私は一種の多目的であるこの拡張機能を持っています:

    public static bool IsNumeric(this object value)
    {
        if (value == null || value is DateTime)
        {
            return false;
        }

        if (value is Int16 || value is Int32 || value is Int64 || value is Decimal || value is Single || value is Double || value is Boolean)
        {
            return true;
        }

        try
        {
            if (value is string)
                Double.Parse(value as string);
            else
                Double.Parse(value.ToString());
            return true;
        }
        catch { }
        return false;
    }

他のデータ型でも機能します。あなたがやりたいことのためにうまくいくはずです。

于 2012-05-01T17:34:37.543 に答える
0

以下のように正規表現を使用します。

if (txtNumeric.Text.Length < 0 || !System.Text.RegularExpressions.Regex.IsMatch(txtNumeric.Text, "^[0-9]*$")) {
 MessageBox.show("add content");
} else {
 MessageBox.show("add content");
}
于 2020-08-14T10:33:28.033 に答える