我有一个表单,我对我的文本框执行了验证,如下所示。对于下面的代码,当我按下“清除”按钮时,文本框被清空,然后,当我试图专注于任何文本框时(即,我正在尝试单击任何文本框)输入一些新文本,然后发生 InvalidCastException .. 为什么会这样???
namespace ex_validation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
txtuserid.Validating += new CancelEventHandler(Dovalidation);
txtpassword.Validating += new CancelEventHandler(Dovalidation);
txtage.Validating += new CancelEventHandler(Dovalidation);
btnnextform.Validating += new CancelEventHandler(Dovalidation);
btnclear.Validating += new CancelEventHandler(Dovalidation);
}
public void Dovalidation(object sender, CancelEventArgs e)
{
TextBox t = (TextBox)sender;// " EXCEPTION OCCURS AT THIS LINE "
if (t.Text=="")
{
t.BackColor = System.Drawing.Color.Yellow;// sets the backcolor of the textbox if found empty
e.Cancel = true;// cancel all other events unless user enters something in that relevant textbox
}
else
t.BackColor = System.Drawing.Color.White;
}
private void txtage_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
{
e.Handled = true;
}
}
private void txtage_Leave(object sender, EventArgs e)
{
if (txtage.Text == "")
MessageBox.Show("Age field cannot be left blank");
else
{
int x = System.Convert.ToInt16(txtage.Text);
if (x < 1 || x > 100)
{
MessageBox.Show("Age cannot be above 100 OR below 1", "Prompt Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtage.Clear();
txtage.Focus();
}
}
}
private void btnnextform_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Show();
}
private void btnclear_Click(object sender, EventArgs e)
{
txtuserid.Text = (string)"";
txtpassword.Text = (string)"";
txtage.Text = (string)"";
}
}
}