验证整数

时间:2013-02-22 03:49:30

标签: c# winforms textbox

我想要一个整数的小数点。如果没有小数点,则显示错误消息。

先生,以下代码写在用户控制文本框中。用户给出的最大长度当他访问用户控件时。

以下代码限制用户在最大长度后输入小数点。

请运行代码Sir,

   public virtual int MaximumLength { get; set; }
    private void txtCurrency_KeyPress(object sender, KeyPressEventArgs e)
    {
        txtCurrency.MaxLength = MaximumLength + 3;
        int dotIndex = txtCurrency.Text.IndexOf('.');
        if (e.KeyChar != (char)Keys.Back)
        {
            if (char.IsDigit(e.KeyChar))
            {
                if (dotIndex != -1 && dotIndex < txtCurrency.SelectionStart && txtCurrency.Text.Substring(dotIndex + 1).Length >= 2)
                {
                    e.Handled = true;
                }
                else if (txtCurrency.Text.Length == MaximumLength)
                {
                    if (e.KeyChar != '.')
                    { e.Handled = true; }
                }
            }
            else
            {
                e.Handled = e.KeyChar != '.' || dotIndex != -1 || txtCurrency.Text.Length == 0 || txtCurrency.SelectionStart + 2 < txtCurrency.Text.Length;
            }
        }`enter code here`

2 个答案:

答案 0 :(得分:0)

decimal myValue = 12.4m;
int value = 0;

if (myValue - Math.Round(myValue) != 0)
{
throw new Exception("Has a decimal point");
}
else
{
value = (int)myValue;
}

答案 1 :(得分:0)

您可以使用RegularExpressions

private void textBox2_Validating(object sender, CancelEventArgs e)
{
    Regex r = new Regex(@"^\d+.\d{0,1}$");
    if (r.IsMatch(textBox2.Text))
    {
        MessageBox.Show("Okay");
    }
    else
    {
        e.Cancel = true;
        MessageBox.Show("Error");
    }
}

<强>更新

private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar)
        && e.KeyChar != '.')
        e.Handled = true;

    if (e.KeyChar == '.'
        && (textBox2).Text.IndexOf('.') > -1) //Allow one decimal point
        e.Handled = true;
}