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

if combobox not selected any item enter empty string to access data base

Hi guys when I enter a data to access data base if I do not select any item in combobox it give me error of null exception So how I can make that if I did not selected any item automatically put empty data to my data base

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