Graeme_Grant's suggestion of the
finally
block is good, but unnecessary - since you have a
using
block around each element, the object created in it is Disposed when you leave the block by any means, which means it is automatically Closed as well.
using (type variableName = new type())
{
... variableName exists here ...
}
... variableName is out of scope here, and Dispose (and Close) have already been called on it ...
But he is right that you overwrite your error message. I'd do it like this:
private void MyButton_Click(object sender, EventArgs e)
{
using (var conn = new SQLiteConnection($"Data Source = '{dbName}';Version=3;"))
{
conn.Open();
string sql = "INSERT INTO FriendsData " +
" (fxFirstName, fxLastName, fxAddress, fxCity, fxState, fxZip, fxCellPhone, fxEmail, fxInfo) " +
" VALUES " +
" (@fxFirstName, @fxLastName, @fxAddress, @fxCity, @fxState, @fxZip, @fxCellPhone, @fxEmail, @tfxInfo)";
string result = "Data Saved";
using (var cmd = new SQLiteCommand(sql, conn))
{
try
{
cmd.Parameters.AddWithValue("@fxFirstName", tbFirstName.Text.Trim());
cmd.Parameters.AddWithValue("@fxLastName", tbLastName.Text.Trim());
cmd.Parameters.AddWithValue("@fxAddress", tbAddress.Text.Trim());
cmd.Parameters.AddWithValue("@fxCity", tbCity.Text.Trim());
cmd.Parameters.AddWithValue("@fxState", tbState.Text.Trim());
cmd.Parameters.AddWithValue("@fxZip", tbZip.Text.Trim());
cmd.Parameters.AddWithValue("@fxCellPhone", mtbCellPhone.Text.Trim());
cmd.Parameters.AddWithValue("@fxEmail", tbEmail.Text.Trim());
cmd.Parameters.AddWithValue("@fxInfo", rtbInfo.Text.Trim());
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
result = ex.ToString();
}
}
}
tbMessage.Text = result;
btnSave.Enabled = false;
}