Windows Forms: Change ConnectionString at Runtime with App.config in C#
By FoxLearn 7/3/2017 9:31:29 PM 33.02K
How to change ConnectionString dynamically in C#
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "DynamicallyConnectionString" and then click OK
Step 2: Design your form as below
Step 3: Add a connection string to the app.config file as below
<configuration> <connectionStrings> <add name="cn" connectionString="Data Source=.;Initial Catalog=Northwind;User ID=sa;Password=123@qaz?;" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>
Step 4: Create an AppSetting class to get the connection string in the app.config file
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DynamicallyConnectionString { public class AppSetting { Configuration config; public AppSetting() { config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); } //Get connection string from App.Config file public string GetConnectionString(string key) { return config.ConnectionStrings.ConnectionStrings[key].ConnectionString; } //Save connection string to App.config file public void SaveConnectionString(string key,string value) { config.ConnectionStrings.ConnectionStrings[key].ConnectionString = value; config.ConnectionStrings.ConnectionStrings[key].ProviderName = "System.Data.SqlClient"; config.Save(ConfigurationSaveMode.Modified); } } }
Step 5: Create a SqlHelper class to check connection to sql server
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DynamicallyConnectionString { public class SqlHelper { SqlConnection cn; public SqlHelper(string connectionString) { cn = new SqlConnection(connectionString); } public bool IsConnection { get { if (cn.State == System.Data.ConnectionState.Closed) cn.Open(); return true; } } } }
Step 6: Add code to handle your form as below
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace DynamicallyConnectionString { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnConnect_Click(object sender, EventArgs e) { string connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", cboServer.Text, txtDatabase.Text, txtUsername.Text, txtPassword.Text); try { SqlHelper helper = new SqlHelper(connectionString); if (helper.IsConnection) MessageBox.Show("Test connection succeeded.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch(Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void Form1_Load(object sender, EventArgs e) { //Add server name to combobox cboServer.Items.Add("."); cboServer.Items.Add("(local)"); cboServer.Items.Add(@".\SQLEXPRESS"); cboServer.Items.Add(string.Format(@"{0}\SQLEXPRESS", Environment.MachineName)); cboServer.SelectedIndex = 3; } private void btnSave_Click(object sender, EventArgs e) { //Set connection string string connectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};", cboServer.Text, txtDatabase.Text, txtUsername.Text, txtPassword.Text); try { SqlHelper helper = new SqlHelper(connectionString); if (helper.IsConnection) { AppSetting setting = new AppSetting(); setting.SaveConnectionString("cn", connectionString); MessageBox.Show("Your connection string has been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
VIDEO TUTORIALS
- Windows Forms: Text to speech in C#
- Windows Forms: Print Picture Box in C#
- Windows Forms: Advanced Filter DataGridView in C#
- Windows Forms: Progress Bar in C#
- How to create a Lucky Draw games in C#
- Windows Forms: Youtube Search with Paging in C#
- Windows Forms: How to Create a Random Password Generator in C#
- Windows Forms: Tag Control in C#
Categories
Popular Posts
Visual Studio: Auto increment version
04/01/2024
What is ARM architecture?
04/01/2024