I need to connect C# with 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 in 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 was Unhandled Configuration system failed to initialize
Can anyone help me please ?
Advertisement
Answer
Try:
var connectionString = ConfigurationManager.ConnectionStrings["Test1"].ConnectionString;
You’re referencing Conn
as the connection string name but referenced it as Test1
in the App.Config