私はフォームを持っており、以下に指定されているようにテキストボックスで検証を実行しました..以下のコードでは、「クリア」ボタンを押すとテキストボックスが空になり、テキストボックスに集中しようとすると(つまり、テキストボックスをクリックしようとしています)新しいテキストを入力しようとすると、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)"";
}
}
}