如果组合框没有选择任何项目,请在Access数据库中输入空字符串

本文关键字:数据库 Access 输入 字符串 请在 组合 有选择 项目 任何 如果 | 更新日期: 2023-09-27 18:14:16

当我在Access数据库中输入数据时,如果我没有在组合框中选择任何项,则会得到null异常的错误。那么,如果我没有选择任何项,如何确保将空数据插入到数据库中呢?

OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "''db''it.accdb");
if (comboBox10.SelectedItem == null)
{
    comboBox10.Text = " ";
}
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();

如果组合框没有选择任何项目,请在Access数据库中输入空字符串

您可以检查SelectedItem属性是否为空,然后设置一个临时变量在您的查询字符串中使用。

string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;

然后在查询字符串中使用comboBox10Text。

编辑:

// Check if comboBox10.SelectedItem is null, set temp variable
string comboBox10Text = comboBox10.SelectedItem == null ? String.Empty : comboBox10.Text;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
// Update query string to use comboBox10Text instead of accessing SelectedItem
cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10Text + "')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("Data Inserted Successfully");
con.Close();

您可以进行空检查并更改条件

If(comboBox10.SelectedItem != null)
{
  cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + comboBox10.SelectedItem.ToString() + "')";
}
else
{
  cmd.CommandText = "insert into data ([Auto Date],AKA,[Phone Number],[R ID],[Related Phone],[Profession]) values ('" + textBox1.Text + "','" + textBox12.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "','" + "" + "')";
}