-1

我想要一个整数中的小数点。如果小数点不存在,则显示错误消息。

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

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

请运行代码先生,

   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`
4

2 回答 2

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;
}
于 2013-02-22T03:55:12.657 回答
0

您可以使用正则表达式

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;
}
于 2013-02-22T04:00:26.290 回答