C# 如何在c中将字符串设为空以转换文本框#
当我在文本框中输入空值时,我遇到异常未处理页面。当用户在文本框中输入空值时,我想显示一个错误消息框我该怎么做C# 如何在c中将字符串设为空以转换文本框#,c#,null,textbox,integer,is-empty,C#,Null,Textbox,Integer,Is Empty,当我在文本框中输入空值时,我遇到异常未处理页面。当用户在文本框中输入空值时,我想显示一个错误消息框我该怎么做 namespace Random_çalışması { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Random rnd = new Random();
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
来更好地捕获转换错误:
您也可以将按钮设置为默认禁用,并在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);
}