CONTEXT: I am writing a WPF app. It works with a SQL Server database in which I put some data, concretely the strings Titulo and Descripcion, the int XP and the string fotoMision. When I click a button the program is supposed to save this data in the database.
PROBLEM: when I click the button it throws me an exception in string connection’s line showing that the object is not instanced. If I put these first lines right below the InitializeComponent(); line the second one doesn’t recognise the miConexion string. Why does that happen and how can I fix it?
CODE:
static string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString;
SqlConnection miConexionSql = new SqlConnection(miConexion);
private void Button_Click(object sender, EventArgs e)
{
string consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision";
SqlCommand miSqlCommand = new SqlCommand(consulta, miConexionSql);
miConexionSql.Open();
miSqlCommand.Parameters.AddWithValue("@Titulo", tituloMision);
miSqlCommand.ExecuteNonQuery();
miConexionSql.Close();
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Connections are meant to be short-lived, i.e. you should create one when the button is clicked and then dispose it right after you have executed the query. Using a using statement implicitly disposes the IDisposable:
private void Button_Click(object sender, EventArgs e)
{
const string Consulta = "INSERT INTO datosMisiones (Titulo, Descripcion, XP, fotoMision) VALUES (tituloMision, descripcionMision, xpMision, nuestroIconoMision";
string miConexion = ConfigurationManager.ConnectionStrings["myProgress.Properties.Settings.DatosHabilidades"].ConnectionString;
using (SqlConnection miConexionSql = new SqlConnection(miConexion))
using (SqlCommand miSqlCommand = new SqlCommand(Consulta, miConexionSql))
{
miConexionSql.Open();
miSqlCommand.Parameters.AddWithValue("@Titulo", tituloMision);
miSqlCommand.ExecuteNonQuery();
miConexionSql.Close();
}
}
Method 2
The format of your connection string for a SQL Server Database should be like so:
"Data Source=DNS_or_IP_Address;Initial Catalog=DatabaseName;User Id=MyUser;Password=MyPassword"
Connection Strings and Examples for various databases
Method 3
put connectionstring on form_load event
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0