這樣在KEY入就檢查各個單字是否可輸入
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int ascii = Convert.ToInt16(e.KeyChar);
if ((ascii >= 97 && ascii <= 122) || (ascii == 8))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
或是用Validating來做驗證
private void textBox1_Validating(object sender, CancelEventArgs e)
{
try
{
int numberEntered = int.Parse(textBox1.Text);
if (numberEntered < 1 || numberEntered > 10)
{
e.Cancel = true;
MessageBox.Show("You have to enter a number between 1 and 10");
}
}
catch (FormatException)
{
e.Cancel = true;
MessageBox.Show("You need to enter an integer");
}
}
第一個是一輸入的時候就檢查
第二個是整個輸入結束執行時檢查
沒有留言:
張貼留言