I have a combobox with two items. And if one is selected I want to write data to "salary" table and if selected another, to "other" table.
The difference between two code blocks is only one word. I would like to know how I could avoid repeating same code twice.
string myConnection = "datasource=localhost; port=3306; username=root;password=root";
if (comboBox4.SelectedItem.ToString() == "Salary")
{
string insert = "insert into budget.salary (name, suma) values (@name, @price);";
using (var conDataBase = new MySqlConnection(myConnection))
using (var cmdDataBase = new MySqlCommand(insert, conDataBase))
{
cmdDataBase.Parameters.AddWithValue("@name", name);
cmdDataBase.Parameters.AddWithValue("@price", suma);
conDataBase.Open();
cmdDataBase.ExecuteNonQuery();
MessageBox.Show("Saved");
}
}
if (comboBox4.SelectedItem.ToString() == "Other")
{
string insert = "insert into budget.other (name, suma) values (@name, @price);";
using (var conDataBase = new MySqlConnection(myConnection))
using (var cmdDataBase = new MySqlCommand(insert, conDataBase))
{
cmdDataBase.Parameters.AddWithValue("@name", name);
cmdDataBase.Parameters.AddWithValue("@price", suma);
conDataBase.Open();
cmdDataBase.ExecuteNonQuery();
MessageBox.Show("Saved");
}
}
insert
used anywhere! \$\endgroup\$