2013-02-22 71 views
-1

我想要一个Integer中的小数点。如果小数点不在那里,它显示错误消息。验证整数

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

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

请运行该代码爵士,

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` 
+3

伟大的...你有什么试过吗? – 2013-02-22 03:50:52

+0

我不明白...有什么想法吗? – 2013-02-22 03:54:30

回答

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; 
} 
+0

先生,我怀疑那是什么“myValue”? – 2013-02-22 04:02:39

+0

对不起,我编辑了我的答案。 'decimal myValue = 12.4m;' – 2013-02-22 04:04:42

+0

不应该使用floor而不是round? – SztupY 2013-02-22 04:12:47

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"); 
    } 
} 

UPDATE:

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; 
} 
+0

先生,我想在KeyPress Event.But上面的代码不支持小数点。我只是试过。 – 2013-02-22 04:06:19

+0

请更改您的问题并查看我的更新答案。 – spajce 2013-02-22 04:10:16

+0

先生,您的回复对我有帮助先生。先生,我想向你展示我的代码,先生。先生,怎么可能?我正在使用用户控件。 – 2013-02-22 04:17:47