写一个windows应用程序的触发事件代码,怎能当客户在textBox里面输入的字符内容超过多少个时,会在label的Text中提示不能超过!!
还有,运行下面这个事件,当我输入数字时label会提示,可是当我输入其他字符时,就运行不了,为什么,怎么改呢??
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (Convert.ToInt64(textBox1.Text )>= 0 || Convert.ToInt64(textBox1.Text) <= 9)
{ label2.Text = "不能输入数字!!"; }
}帮帮忙
还有,运行下面这个事件,当我输入数字时label会提示,可是当我输入其他字符时,就运行不了,为什么,怎么改呢??
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (Convert.ToInt64(textBox1.Text )>= 0 || Convert.ToInt64(textBox1.Text) <= 9)
{ label2.Text = "不能输入数字!!"; }
}帮帮忙
这个方法Convert.ToInt64()在参数为非数字时,转换失败,就出错了
{
int value = Convert.ToInt32("Hello");
}
catch (Exception)
{
// exception occurs here
}
因为你输入的值不是数字啊,你用>= 0,<= 9不就是要和数字进行比较的吗
应该在KeyPress中,用下正则
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Regex.IsMatch(e.KeyChar.ToString(), @"\d"))
{
label2.Text = "不能输入数字!!";
}
}
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[0-9]"))
{
label2.Text = "不能输入数字";
e.Cancel = true;
}
else
{
if (textBox1.Text.Length > 9)
{
label2.Text = "不能超过9个字符";
e.Cancel = true;
}
}
}还有专用于提示用户的控件ErrorProvider...例:
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[0-9]"))
{
errorProvider1.SetError((Control)sender, "不能输入数字");
e.Cancel = true;
}
else
{
if (textBox1.Text.Length > 9)
{
errorProvider1.SetError((Control)sender, "不能超过9个字符";
e.Cancel = true;
}
}
}
不过对于楼主的想法 也可以判断 KEYPRESS事件 或者 TEXTCHANGE事件。