2013-08-18 39 views
0

我在运行项目时遇到错误。我想,如果TextBox1的是empty.My代码来创建一个if语句是这样的:不能将类型'字符串'转换为'bool'

 SqlCommand cmd = new SqlCommand(" DELETE from Records WHERE ([Student ID]='" + textBox1.Text + "')", con); 
     MessageBox.Show("Data Deleted!", "Information ... ", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); 

     textBox1.Text = " "; 

     if (textBox1.Text = " ") 
     { 
      MessageBox.Show("Please enter Student ID", "Delete Failed",MessageBoxButtons.OK,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1); 
     } 
     cmd.ExecuteNonQuery(); 
     con.Close(); 

错误是texbox1.Text =“”

+2

你是不是指'textBox1.Text ==“”'?使用'=='你**比较**,使用'='你**指定**。 – user2674389

+3

尝试使用string.IsNullOrWhiteSpace() – Miller

+0

即使没有编译错误,当您自己分配文本时,代码完全没有意义。 –

回答

3

变化

if (textBox1.Text = " ") 

if (textBox1.Text == " ") 

=赋值运算符==平等运营商

赞;

SqlCommand cmd = new SqlCommand(" DELETE from Records WHERE [Student ID] = @studentID", con); 
cmd.Parameters.AddWithValue("@studentID", textBox1.Text); 
MessageBox.Show("Data Deleted!", "Information ... ", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); 

textBox1.Text = " "; 

if (String.IsNullOrWhiteSpace(textBox1.Text)) 
{ 
    MessageBox.Show("Please enter Student ID", "Delete Failed",MessageBoxButtons.OK,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1); 
} 
cmd.ExecuteNonQuery(); 
con.Close(); 

你应该总是用parameterized queries,这种代码是开放的SQL Injection攻击。

而使用String.IsNullOrWhiteSpace方法更合乎逻辑。

指示指定的字符串是否为空,空白或仅包含空格字符的 。

顺便说一句,因为你自己assingning你的文字,这两条线是meaningles ..

textBox1.Text = " "; 

if (String.IsNullOrWhiteSpace(textBox1.Text)) 
+0

我有另一个问题。当我在textbox1中输入空值或什么都没有。出现的信息框是数据删除,然后会出现另一个消息框,说明请输入学号。 –

+0

@JvCam这很正常,因为如果你的'textBox1'是_empty_,'String.IsNullOrWhiteSpace(textBox1.Text)'返回'true',这就是你的if语句工作的原因。 –

+0

但是我输入一个空值,它应该只显示消息框“请输入学生ID”。消息框“数据已删除不应显示。 –

5

您是实现平等与=,这台比较一个值。

相反,您需要使用等号运算符==

6

这是你的问题的根源: if (textBox1.Text = " ")

=是赋值运算符。您想使用==进行比较。

另一种选择是使用string.IsNullOrWhiteSpace。如果字符串是null,""或任何数量的空白,则返回true。

E.g. if (string.IsNullOrWhiteSpace(textBox1.Text))

另外,您的SQL容易受到SQL注入漏洞的影响。请使用参数化查询。

+0

感谢您的答案。对不起这个问题我只是一个新手在编程 –

+1

@JvCam我们都是以新手的身份出现的!祝你好运。 –

3

这应该工作。

SqlCommand cmd = new SqlCommand(" DELETE from Records WHERE ([Student ID]='" + textBox1.Text + "')", con); 
     MessageBox.Show("Data Deleted!", "Information ... ", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); 

     textBox1.Text = " "; 

     if (textBox1.Text == " ") 
     { 
      MessageBox.Show("Please enter Student ID", "Delete Failed",MessageBoxButtons.OK,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1); 
     } 
     cmd.ExecuteNonQuery(); 
     con.Close(); 
1

您还可以使用

if(textBox1.Text.trim()=="") 
{ 

MessageBox.Show("Please enter Student ID", "Delete Failed",MessageBoxButtons.OK,MessageBoxIcon.Error,MessageBoxDefaultButton.Button1);  
} 
cmd.ExecuteNonQuery();} 

这也是拉手whitspace “”。

相关问题