4

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 ?

1
  • You do not seem to be referring to the correct key in the App.config file. In your code you try to read a connection string named "Conn", while the one you configured is called "Test1" Commented Mar 12, 2013 at 11:59

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

Try this..

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

Comments

2

Try below code and then check

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.