这是我制作的表格
当我在文本框中输入一个空值时,我遇到了未处理的异常页面。当用户在文本框中输入空值时,我想显示一个错误消息框,我该怎么做?
namespace Random_çalışması
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random rnd = new Random();
int number;
int answer;
private void button1_Click(object sender, EventArgs e)
{
number = rnd.Next(1, 101);
label1.Text = number.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
answer = Convert.ToInt32(textBox1.Text);
if(answer == number)
{
MessageBox.Show("Welcome to the page", "Welcome!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if(String.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Icorrect entrance", "You can not acces to the page", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Icorrect entrance", "You can not acces to the page", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
只需在方法的开头添加空测试:
private void button2_Click(object sender, EventArgs e)
{
if ( textBox1.Text == "" )
{
MessageBox.Show(...);
return;
}
answer = Convert.ToInt32(textBox1.Text);
...
}
您也可以使用int.TryParse()
而不是Convert
来更好地捕捉转换错误:。
int.TryParse如何实际工作
您也可以简单地将按钮设置为默认禁用,并在TextChanged
事件上添加此处理程序:
private void textBox1_TextChanged(object sender, EventArgs e)
{
button.Enable = textBox1.Text != "";
}
也可以在这里执行int.TryParse
:
private void textBox1_TextChanged(object sender, EventArgs e)
{
button.Enable = textBox1.Text != "" && int.TryParse(textBox1.Text, out _);
}
因此,只有在不为空且可转换且用户体验一致的情况下,该按钮才会启用。
现在按钮点击处理程序是:
private void button2_Click(object sender, EventArgs e)
{
answer = Convert.ToInt32(textBox1.Text);
if ( answer == number )
MessageBox.Show("Welcome to the page", "Welcome!", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("Icorrect entrance", "You can not acces to the page", MessageBoxButtons.OK, MessageBoxIcon.Error);
}