A Simple Way to Change SQL Server Connection String Programmatically in C#

Introduction

In this article I am intending to describe a simple way to change SQL Server database connection string programmatically while the application is running. By this way you can also change server .

Step 1

Create a Windows Form Application,

create

Step 2

Create two strings in project -> DBChangeApp Properties -> Settings as Property.settings.default.strServer and Property.settings.default.strDBConnection.

setting

Step 3

Attach or create a data basewith the data connection wizard. And create a table with one column and insert data to the table.

Step 4

Create a Windows Form with two textboxes and one combo box and three buttons.

form

Step 5

Enter following code,

code

Step 6

Enter following code in form Load event. If we have set a database connection, this will be connected and show details in text boxes.
code

Step 7

Database Open button click event. This will find database and store the file path in the properties variable as in Properties.Settings.Default.strDBConnection.

code
Step 8

“Change database” button click event.

In this event we will store server in the property string as in Properties.Settings.Default.strServer. And we store the new connection string.

code

Last Step

Select data from data base with select statement and store the same in Combo Box.