Hi I wish to know how to define a connection string and use it successfully in my App. The Idea is to define once and use as required.
I followed the advice here :
How to get Connection String from App.Config in C#[
^]
with little success. when i run my test app, it runs ok but when i ask it to insert sole values into the test database I created for the occasion i have an error message:
" Object reference is not defined to an instance of the object " at the level of the statement
var connectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
What should I do to get this situation sorted out please ?
What I have tried:
1. First I added this code in the config.app file:
<connectionStrings>
<add name= "con"
providerName= "System.Data.SqlClient"
connectionString="Data Source=.\sqlexpress;Initial Catalog=practice;Integrated Security=True" />
</connectionStrings>
2. Next I Added a reference to System.Configuration
3. The click event of my button control has the code :
var connectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string ins = @"insert into employee(name, address, phonenum, profession) values(@nam, @add, @phonen, @job)";
SqlCommand cmd = new SqlCommand(ins, con);
SqlParameter NM = new SqlParameter();
NM.ParameterName = "nam";
NM.Value = nametxt.Text;
SqlParameter AD = new SqlParameter();
AD.ParameterName = "add";
AD.Value = addresstxt.Text;
SqlParameter PN = new SqlParameter();
PN.ParameterName= "phonen";
PN.Value = telephonetxt.Text;
SqlParameter PF = new SqlParameter();
PF.ParameterName = "job";
PF.Value = professiontxt.Text;
cmd.Parameters.Add(AD);
cmd.Parameters.Add(PN);
cmd.Parameters.Add(NM);
cmd.Parameters.Add(PF);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Values Entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();