-2

I am connecting to the database with the code below

     string connString = @"Data source = test2 ; Database=test1data ; User Id=a ; Password=test1234";
   using (SqlConnection sqlConn = new SqlConnection(connString))
            {
                string sqlQuery = @"SELECT * from Zone";
                SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable table = new DataTable();
                da.Fill(table);
                dataGridView1.DataSource = new BindingSource(table, null);
            }

But I wanted to create a file to connect that could be changed.

For example:

I'm connecting to a database, but changing this file I'll connect to another database

Pedro Azevedo
  • 228
  • 4
  • 12

1 Answers1

0

Add a <connectionStrings> section to your App.config/Web.config file.

<configuration>
  <connectionStrings>
    <add name="{your connection name}" connectionString="{your connection string}" />
  </connectionStrings>
...
</configuration>

Read it using the ConfigurationManager

using System.Configuration;

var connectionString = 
    ConfigurationManager.ConnectionStrings["{your connection name}"].ConnectionString;

See ConfigurationManager.ConnectionStrings

Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36