c#初学者如何使用if语句来检查文本框为空
本文关键字:文本 检查 语句 初学者 何使用 if | 更新日期: 2023-09-27 18:29:04
我正在使用textbox将数据插入数据库。但是,我不想在数据库中插入null或空值。如何使用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);
}
}
您可以使用string.IsNullOrEmpty
或string.IsNullOrWhiteSpace
方法来检查字符串是否为空或仅包含空格。
您还应该避免使用+
加入查询。更好地使用并列查询。实例
这样尝试:
if (string.IsNullOrWhiteSpace(MyTextBox.Text))
{
//some message
}
这也将处理空白(如果它出现在您的文本框中)
附带说明:
您的代码容易出现SQL注入。您应该更好地尝试使用参数化查询来处理它。
将此条件放在方法的开头
if(string.IsNullOrWhiteSpace(TextBox1.Text))
{
MessageBox.Show("Empty value");
return;
}
如下所示使用。希望它能解决你的问题
if(!string.IsNullOrEmpty(txtYourTextBox.Text))
{
//Logic here if text box is not empty
}
了解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);
}
}