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
Use the property SelectedValue
for comboboxes instead of Text
. Also assign DBNull.Value
or default value to the parameters @Reason
and @Transfer
if the cmbStatus.Text != "Transfered".
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);
}
Consider the parameterized query that you are using, it expecting four parameters as you specified in the query So you should five the four otherwise you will get that error as you described in the question; What you can do in this situation is :
cmd = con.CreateCommand();
if (cmbStatus.Text == "Transfered")
{
cmd.CommandText = "Insert Into tb_data(No_RM,Status,Reason,Transfer)Values(@No_RM,@Status,@Reason,@Transfer)";
cmd.Parameters.AddWithValue("@Reason", cmbReason.Text);
cmd.Parameters.AddWithValue("@Transfer", cmbTransfer.Text);
}
else
{
cmd.CommandText = "Insert Into tb_data(No_RM,Status)Values(@No_RM,@Status)";
}
cmd.Parameters.AddWithValue("@NO_RM", txtNo_Rm.Text);
cmd.Parameters.AddWithValue("@Status", cmbStatus.Text);
cmd.ExecuteNonQuery();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.