0

运行项目时出现错误。如果 textbox1 为空,我想创建一个 if 语句。我的代码是这样的:

        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 = " "

4

5 回答 5

6

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

=是赋值运算符。您想==用于比较。

另一种选择是使用string.IsNullOrWhiteSpace. 如果字符串是 , 或任意数量的空格,则返回nulltrue ""

例如 if (string.IsNullOrWhiteSpace(textBox1.Text))

顺便说一句,您的 SQL 容易受到 SQL 注入漏洞的攻击。请使用参数化查询。

于 2013-08-18T13:47:24.337 回答
5

您正在比较与 的相等性=,它设置了一个值。

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

于 2013-08-18T13:47:19.797 回答
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();
于 2013-08-18T13:51:00.310 回答
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();

而且您应该始终使用参数化查询,这种代码对SQL 注入攻击是开放的。

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

指示指定的字符串是 null、空还是仅包含空白字符。

顺便说一句,既然你自己分配你的文字,这两行是没有意义的..

textBox1.Text = " ";

if (String.IsNullOrWhiteSpace(textBox1.Text)) 
于 2013-08-18T13:47:56.700 回答
1

你也可以使用

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

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

这也处理空白“”。

于 2013-08-18T16:02:31.623 回答