Configuration Manager for SqlConnection

Reading Time: 1 minute

In this tutorial, it is explained how to use Configuration Manager for SqlConnection. Firstly, we need to add Configuration Manager as reference to the project.

Choose System.Configuration

Use namespace using System.Configuration;

Then we are ready to use Configuration Manager for SqlConnection.
Remember: in order to use Connection String via Configuration Manager,  we need to use <connectionStrings> in App.config as is it is described already  by using data connection data set.

Now we can use ConnectionString method of the ConfigurationManager class in order to obtain SqlConnection object. For example:

string connectionString = ConfigurationManager.ConnectionStrings[“ConnectionToTheDataBase”].ConnectionString;

Then use this connectionString as following:

SqlConnection connection = new SqlConnection(connectionString);

And of course, namespace using System.Data.SqlClient; We can also use namespace using System.Collections; and then use approach in ADO.NET access to the database as we get used to it:

try
{

var connectionString = ConfigurationManager.ConnectionStrings[“ConnectionToTheDataBase”].ConnectionString;

var connection = new SqlConnection(connectionString);

connection.Open();

var command = new SqlCommand(“SELECT * FROM dept ORDER BY deptname ASC “, connection);

SqlDataReader sqlrdReader = command.ExecuteReader();

while (sqlrdReader.Read())

{

ltbxSmerovi.Items.Add(sqlrdReader[“deptname”].ToString());

alSmeroviId.Add(sqlrdReader[“deptid”]);

}

connection.Close();

}
catch (Exception ex)
{

MessageBox.Show(ex.ToString());

}

Tagged with: ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*