如何禁止在textBox中引入字母?也就是说,这种结构不正确
public void textBox1_KeyDown(object sender, KeyEventArgs e)
{
try
{
char s = Convert.ToChar(textBox1.Text);
if ((s <= '0') || (s >= '9'))
MessageBox.Show("You have entered a symbol! Please enter a number");
}
catch (System.FormatException)
{
MessageBox.Show("You have entered a symbol! Please enter a number");
}
}
答案 0 :(得分:1)
您需要检查在KeyDown事件(e.Key属性)中输入的密钥,因为在事件发生后将键值添加到Text字段或使用TextChanged事件 - 这将捕获cut&amp;粘贴操作。
public void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
if (!ValidNumericString(textBox1.Text))
{
MessageBox.Show("You have entered invalid characters! Please enter a number");
Dispatcher.BeginInvoke(new Action(() => textBox1.Undo()));
e.Handled = true;
}
}
public bool ValidNumericString(string IPString)
{
return IPString.All(char.IsDigit);
// OR make this check for thousands & decimals if required
}
答案 1 :(得分:1)
您可以使用OnKeyPress事件,如果您愿意,可以手动取消键事件。
void textBox1_OnKeyPress(KeyPressEventArgs e)
{
e.Handled = true; // this won't send the key event to the textbox
}
如果您只想接受数字和相关字符(负号,小数分隔符......),您可以测试输入的字符:
void textBox1_OnKeyPress(KeyPressEventArgs e)
{
NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
string groupSeparator = numberFormatInfo.NumberGroupSeparator;
string negativeSign = numberFormatInfo.NegativeSign;
string keyInput = e.KeyChar.ToString();
e.Handled = !(Char.IsDigit(e.KeyChar) || keyInput.Equals(negativeSign) || keyInput.Equals(decimalSeparator) || keyInput.Equals(groupSeparator));
}
这是未经测试的代码,因为我在工作,但你明白了。
答案 2 :(得分:0)
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (Control.ModifierKeys == Keys.Control) return; // Check if ctrl is pressed
var key = (char) e.KeyValue; // ASCII to char
if (char.IsDigit(key) || char.IsControl(key) || char.IsWhiteSpace(key)) return; // Check if "key" is a number
MessageBox.Show("You have entered a symbol! Please enter a number");
textBox1.Text = textBox1.Text.Substring(0, textBox1.Text.Length - 1); // Remove last element
textBox1.SelectionStart = textBox1.Text.Length; // Return to initial position
}