baban jamal baban jamal - 1 month ago 13
C# Question

If combobox not selected any item enter empty string into Access database

When I enter a data in my Access database, if I do not select any item in the combobox, I get an error of null exception. So how can I make sure that if I did not select any items, empty data is inserted into my database?

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();

Answer

You can check if the SelectedItem property is null, then set a temp variable to use in your query string.

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

Then use comboBox10Text in your query string.

Edit:

// 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();