判断输入是否为空

亚旺 2011-05-14 06:10:28
string a = textBox1.Text.Trim();
int d =int.Parse( textBox2.Text.Trim());
if (string.IsNullOrEmpty(a))
{
MessageBox.Show("a不能为空");
}
else if (string.IsNullOrEmpty(b))
{
MessageBox.Show("b 不能为空");
}

上面的例子是判断输入的是否为空,请问这样做是否正确,这是连接到数据库的中一部分代码,当我运行时这里string.IsNullOrEmpty(b)显示不正确,请问要怎样更改呢?
...全文
166 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
remember_me 2011-05-14
  • 打赏
  • 举报
回复
先用string.IsNullOrEmpty()方法来进行判断,然后在对数据进行操作。


if(string.IsNullOrEmpty(this.textBox2.Text.Trim()))
{
//操作
}


如果你先用int.Parse()方法进行判断,很有可能出现异常。
不懂 2011-05-14
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 jy02349551 的回复:]
C# code

if (string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("a不能为空");
}
else if (string.IsNullOrEmpty(textBox2.Text.Trim()))
{
MessageBox.Show("b 不能为空");
}
strin……
[/Quote]
修改一下

if (string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("a不能为空");
}
if (string.IsNullOrEmpty(textBox2.Text.Trim()))
{
MessageBox.Show("b 不能为空");
}
string a = textBox1.Text.Trim();
int d =int.Parse( textBox2.Text.Trim());


不懂 2011-05-14
  • 打赏
  • 举报
回复

if (string.IsNullOrEmpty(textBox1.Text.Trim()))
{
MessageBox.Show("a不能为空");
}
else if (string.IsNullOrEmpty(textBox2.Text.Trim()))
{
MessageBox.Show("b 不能为空");
}
string a = textBox1.Text.Trim();
int d =int.Parse( textBox2.Text.Trim());



string 转换int型应该先判断string是否为空,否则int.Parse()方法就报错了。
zhonglisun 2011-05-14
  • 打赏
  • 举报
回复
改成这样就差不多了
string a = textBox1.Text.Trim();
int d =int.Parse( textBox2.Text.Trim());
if (string.IsNullOrEmpty(a))
{
MessageBox.Show("a不能为空");
}
else if (string.IsNullOrEmpty(textBox2.Text.Trim().ToString()))
{
MessageBox.Show("b 不能为空");
}

亚旺 2011-05-14
  • 打赏
  • 举报
回复
string a = textBox1.Text.Trim();
int d =int.Parse( textBox2.Text.Trim());
if (string.IsNullOrEmpty(a))
{
MessageBox.Show("a不能为空");
}
else if (string.IsNullOrEmpty(b))
{
MessageBox.Show("b 不能为空");
}

这个例子要怎样改才可以啊
十八道胡同 2011-05-14
  • 打赏
  • 举报
回复
string.IsNullOrEmpty只是判断string的,你的d是int,你给转换成string.
d.tostring();
暖枫无敌 2011-05-14
  • 打赏
  • 举报
回复

string a = textBox1.Text.Trim();
int d =int.Parse( textBox2.Text.Trim());
if (string.IsNullOrEmpty(a))
{
MessageBox.Show("a不能为空");
}
else if (string.IsNullOrEmpty(d.ToString())) //string.IsNullOrEmpty针对string类型
{
MessageBox.Show("d 不能为空");
}
我姓区不姓区 2011-05-14
  • 打赏
  • 举报
回复
当然不行,string.IsNullOrEmpty判断的是字符串,你的d是个整型,怎么可能编译通过?
else if (string.IsNullOrEmpty(textBox2.Text))
亚旺 2011-05-14
  • 打赏
  • 举报
回复
写错了,应该是d的,但是这样也不行
我姓区不姓区 2011-05-14
  • 打赏
  • 举报
回复
b是什么东西

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧