C#如何判断Textbox 里面的值不能为空

如题所述

如果是winform的话,可以在文本框的LostFocus事件中写如下代码:
if(string.IsNullOrWhiteSpace(TextBox1.Text)){
MessageBox.Show("xxx");
TextBox1.Focus();
}

如果是asp.net的话,就麻烦一些了,你的判定是不能写在后台代码中的,因为后台的代码服务器端代码,要运行服务器端代码需要提交页面。所以,你可以这样做:
前端
<asp:TextBox runat="server" id="txt" />
后置代码:
在page_load中加上这个:
txt.Attributes.Add("onblur", "if(!/\\S+/.test(this.value)) alert('不能为空');");//不完整,具体的你在修正一下好了追问

你好!用你上面说的.IsNullOrWhiteSpace 不行private bool CheckRSVNameBox(ref TextBox textbox)
{if (string.IsNullOrEmpty(txtBox.Text.Trim ()) {
textbox.BackColor = Color.Red;
return false;
}
}
if (!CheckRSVNameBox( ref txtboxRSVName)) {
ErrCount++;
}
文本框name为txtboxRSVName,谢谢

追答

string.IsNullOrWhiteSpace不行,是因为你的vs不是2010,只有.net framework 4.0以上才支持这个方法。
可以使用string.IsNullOrEmpty(Text.Trim())代替。

追问

错误1“XS_DSChecker.PersonInfosDetailForm.CheckNameBox(refSystem.Windows.Forms.TextBox)”: 并非所有的代码路径都返回值
我现在用的是 string.IsNullOrEmpty(txtBox.Text.Trim ()); 代替了; 但是方法提示上的错误信息

追答

private bool CheckRSVNameBox(ref TextBox textbox)
{
if (string.IsNullOrEmpty(textbox.Text.Trim ()) {
textbox.BackColor = Color.Red;
return false;
}
return true;
}

if (!CheckRSVNameBox( ref txtboxRSVName)) {
ErrCount++;
}

提问者很懒!!!

追问

我按照 你上面说的做了,还是不行 ,错误信息错误: 并非所有的代码路径都返回值

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-21
if (textBox1.Text.Trim() == "") //Trim()是去除空格
{
MessageBox.Show("不能为空", "提示");
}追问

private bool CheckRSVNameBox(ref TextBox textbox)
{if (textbox.Text.Trim()=="")
{
textbox.BackColor = Color.Red;
return false;
}
}
if (!CheckRSVNameBox( ref txtboxRSVName)) {
ErrCount++;
}
我这样处理但是不行! 请问一下应该如果应用? 谢谢

第2个回答  2011-12-21
if (string.IsNullOrEmpty(Textbox.Text.Trim()))
第3个回答  2011-12-21
页面加个验证控件。