我使用下面的代码不允许除文本框中的数字之外的任何字符...但它允许'。'字符!我不希望它允许点。
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 :(得分:3)
使用它:
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,它与'。'相同。我不知道为什么喜欢这个。
答案 1 :(得分: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.
}
答案 2 :(得分:0)
在keypress事件中尝试使用此代码来解决您的问题:
private void txtMazaneh_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && (int)e.KeyChar != 8 ||(e.KeyChar= .))
e.Handled = true;
}
答案 3 :(得分:-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;
}
}