1

我正在使用文本框将数据插入数据库。但是我不想在数据库中插入空值或空值。如何使用 if 语句检查文本框是否为空?(这意味着如果文本框为空,则显示所需用户输入数据的对话框)

这是我的代码:

 private void submit_button_Click(object sender, EventArgs e)
        {

        string constring = "datasource=localhost;username=root;password=";
        string Query = "INSERT INTO bug.bug (Bug_ID, title, Type_of_bug, software, software_version, description, step_to_reproduction, severity, priority, symptom) values('" + this.bugid_txt.Text+"', '" + this.title_txt.Text + "','" + this.comboBox1.Text + "','" + this.software_txt.Text + "','" + this.software_version_txt.Text + "','" + this.description_txt.Text + "','" + this.step_to_reproduction_txt.Text + "','" + this.severity_combo.Text + "','" + this.priority_combo.Text + "','" + this.symptom_txt.Text + "')";

        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
        MySqlDataReader myReader;
        try
        {
            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();
            MessageBox.Show("The Bug have been reported");
            while(myReader.Read())
            {

            }
            this.Close();
        }catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
4

5 回答 5

1

您可以使用string.IsNullOrEmptyorstring.IsNullOrWhiteSpace方法检查字符串是否为空或仅包含空格。

您还应该避免使用+. 更好地使用参数化查询。例子

于 2016-01-06T07:47:52.613 回答
1

试试这样:

if (string.IsNullOrWhiteSpace(MyTextBox.Text)) 
{
   //some message
}

这也将处理空格(如果它存在于您的文本框中。)

附带说明:

您的代码容易发生SQL 注入。您最好尝试使用参数化查询来处理它。

于 2016-01-06T07:48:01.470 回答
0

使用如下。希望它能解决你的问题

if(!string.IsNullOrEmpty(txtYourTextBox.Text))
{
   //Logic here if text box is not empty
}
于 2016-01-06T12:13:56.663 回答
0

将此条件放在方法的开头

if(string.IsNullOrWhiteSpace(TextBox1.Text))
{
       MessageBox.Show("Empty value");
       return;
}
于 2016-01-06T07:48:32.480 回答
-1

小心 Sql 注入

 private void submit_button_Click(object sender, EventArgs e)
            {

     if (!string.IsNullOrEmpty(mytextBox))
    {

      MessageBox.Show("your message goes here");
       return ;
     }

        string constring = "datasource=localhost;username=root;password=";
       // insert with parameterised query 

        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
        MySqlDataReader myReader;
        try
        {
            conDataBase.Open();
            myReader = cmdDataBase.ExecuteReader();
            MessageBox.Show("The Bug have been reported");
            while(myReader.Read())
            {

            }
            this.Close();
        }catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
于 2016-01-06T07:49:10.043 回答