When I add a Car in my application I get
The ConnectionString property has not been initialized.
I have the problem of ConnectionString property. I check similar question of mine but I found nothing helpfulness.
I use a class connection named dbConnection.cs:
class dbConnection
{
//Connection to database
private string con = "Data Source=(local)\\SQLEXPRESS; Initial Catalog=MLQ7024; Integrated Security=TRUE".ToString();
public string Con
{
get
{
return con;
}
}
}
This is the code of my button
private void btnAddCar_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(dc.Con))
{
DataTable dtCar = new DataTable();
BindingSource Car_bs = new BindingSource();
using (SqlCommand cmd = new SqlCommand("sp_Add_Car", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
//......
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtCar.Clear();
da.Fill(dtCar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\t" + ex.Source);
}
}
}
refreshCar();
}
This is the code of an another button working well without error
private void btnAddPayment_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(dc.Con))
{
DataTable dtPayment = new DataTable();
using (SqlCommand cmd = new SqlCommand("sp_Add_Paiements", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id_paiement", SqlDbType.Char).Value = txtBoxPaymentId.Text;
cmd.Parameters.Add("@montant", SqlDbType.SmallMoney).Value = txtBoxAmount.Text;
cmd.Parameters.Add("@id_Location", SqlDbType.Char).Value = cmbpaymentLesaseId.Text;
//cmd.Parameters.Add("@status", SqlDbType.Char).Value = txtBoxStatusPayment.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dtPayment.Clear();
da.Fill(dtPayment);
btnAddLease.Hide();
refreshPayments();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\t" + ex.Source);
}
}
}
btnAddPayment.Hide();
}
You aren’t showing where you have initialized your
dbConnectionclass. Changing it all to static will probably help, I’m guessing:If your
dbConnectionclass worked in one method but not the other, chances are you had it initialized in one and not the other. Unless you have to deal with different database connections, using a static class for your database connections is probably the best route.Then you change your calling method like this: