Celcius_Bitz Celcius_Bitz - 3 months ago 17
MySQL Question

C# if certain text selected in combobox winform

i have 3 combobox : cmbStatus,cmbReason,cmbTransfer, primarykey textbox txtNo_RM and the trigger button: btnAdd. Using Mysql as Database

While cmbStatus != "Transfered" cmbReason and cmbTransfer will be intended to not be selected by user. The problem is it didn't work while i use this code

private void btnAdd_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
con.Open();
try
{
cmd = con.CreateCommand();
cmd.CommandText = "Insert Into tb_data(No_RM,Status,Reason,Transfer)Values(@No_RM,@Status,@Reason,@Transfer)";
cmd.Parameters.AddWithValue("@NO_RM", txtNo_Rm.Text);
cmd.Parameters.AddWithValue("@Status", cmbStatus.Text);

if (cmbStatus.Text == "Transfered")
{
cmd.Parameters.AddWithValue("@Reason", cmbReason.Text);
cmd.Parameters.AddWithValue("@Transfer", cmbTransfer.Text);
}
cmd.ExecuteNonQuery();


}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
LoadData();
MessageBox.Show("Data Added!");
}
}



}


code above resulting fatal error message and also using SelectedText.ToString

try adding this code, resulting out of range error

if (cmbStatus.Text != "Transfered")
{
cmd.Parameters.AddWithValue("@Reason", "");
cmd.Parameters.AddWithValue("@Transfer", "");
}


thanks before

Answer

You can use DBValue.Null for empty values like this:

if (cmbStatus.Text == "Transfered")
{
   cmd.Parameters.AddWithValue("@Reason", cmbReason.Text);
   cmd.Parameters.AddWithValue("@Transfer", cmbTransfer.Text);
}
else
{
   cmd.Parameters.AddWithValue("@Reason", DBNull.Value);
   cmd.Parameters.AddWithValue("@Transfer", DBNull.Value);
}
Comments