2012-10-25 22 views
2

我使用下面的代碼來禁止任何字符,除了在文本框中的數字......但它允許'。'字符!我不希望它允許點。無法確定'。' keybox爲文本框KeyPress事件

private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (!char.IsDigit((char)(e.KeyChar)) && 
      e.KeyChar != ((char)(Keys.Enter)) && 
      e.KeyChar != (char)(Keys.Delete) && 
      e.KeyChar != (char)(Keys.Back)&& 
      e.KeyChar !=(char)(Keys.OemPeriod)) 
     { 
      e.Handled = true; 
     } 
    } 
+0

看看[此線索](http://stackoverflow.com/questions/463299/how-do-i- make-a-textbox-that-only-accepts-numbers) – Default

回答

2

使用本:

if (!char.IsDigit((char)(e.KeyChar)) && 
      e.KeyChar != ((char)(Keys.Enter)) && 
      (e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) && 
      e.KeyChar != (char)(Keys.Back) 
      ) 

這是因爲Keys.Delete的char值是46,它與'。'相同。我不知道它爲什麼喜歡這個。

0

你可以代替試試這個(其中textBox1將是你的文本框):

// Hook up the text changed event. 
textBox1.TextChanged += textBox1_TextChanged; 

...

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    // Replace all non-digit char's with empty string. 
    textBox1.Text = Regex.Replace(textBox1.Text, @"[^\d]", ""); 
} 

或者

// Save the regular expression object globally (so it won't be created every time the text is changed). 
Regex reg = new Regex(@"[^\d]"); 

private void textBox1_TextChanged(object sender, EventArgs e) 
{ 
    if (reg.IsMatch(textBox1.Text)) 
     textBox1.Text = reg.Replace(textBox1.Text, ""); // Replace only if it matches. 
} 
+0

它已經在那裏 – Default

+0

@默認是,正在閱讀quick =) –

-1
//This is the shortest way 
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if(!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) 
    { 
     e.Handled = true; 
    } 
} 
0

試試這個代碼在按鍵事件您的問題:

private void txtMazaneh_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     if (!char.IsDigit(e.KeyChar) && (int)e.KeyChar != 8 ||(e.KeyChar= .)) 
      e.Handled = true; 
    }