How can I connect C # with Db using App.config?

I need to connect C # to a SQL Server database using app.config .

My code is:

 public partial class Form1 : Form { string connectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString; public Form1() { InitializeComponent(); } public void InsertDeleteUpdate(string query) { try { SqlConnection Conn = new SqlConnection(connectionString); Conn.Open(); SqlCommand comm = new SqlCommand(query, Conn); comm.ExecuteNonQuery(); Conn.Close(); MessageBox.Show("Succeeded"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } 

and app.config i have:

 <connectionStrings> <add name="Test1" providerName="System.Data.SqlClient" connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" /> </connectionStrings> 

but I get an error and I can’t fix it:

ConfigurationErrorExeption - raw configuration system failed to initialize

Can anybody help me?

+4
source share
3 answers

Try:

 var connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString; 

You refer to Conn as the name of the connection string, but refer to it as Test1 in App.Config

+3
source

Try the code below and then check

 string connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString; 
+2
source

Try it.

  <connectionStrings> <add name="Conn" providerName="System.Data.SqlClient" connectionString="Data Source=KSPR1WS126;Initial Catalog=Test1;User ID=sa" /> </connectionStrings> 
+2
source

All Articles