我有一個表單,我對我的文本框進行了驗證,如下所示。對於下面的代碼,當我按下'清除'按鈕時,文本框被清空,然後,當我試圖專注於任何文本框(即,我試圖點擊任何文本框)輸入一些新的文本,然後發生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)"";
}
}
}
btnnextform和btnclear不是一個文本框-ES我想和你仍然嘗試驗證,如果它是。這是根本原因... – rene