Reputation: 13
In my project I am using a ConnectionString
class. I want to change my ConnectionString
class dynamically in my Winforms application.
I want to create a form (frmServerCon
) where I can input new values in textboxes, like Data Source, Initial Catalog, Username and Password. When I click the "save" button, the code is supposed to save these new settings in the ConnectionString
class and on connect button click it should check if new connection values work for SQL Server before saving.
Right now my ConnectionString
class look like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 7KProject
{
class ConnectionString
{
public string DBConn = "Data Source=TCP/IP,PORT;Initial Catalog=DataBase;User ID=user;Password=*******";
}
}
I am unable to find any solution. It would be great if you can help with some working code. Sorry I have no example code.
Thank you.
Upvotes: 0
Views: 3633
Reputation: 13
i have sort out this problem in other way. I Hope it may help some other people looking for this and i would like to ask to review it if there is any improvement please do suggest.
i am calling app.config connectionString
<connectionStrings>
<add name="DBConn" connectionString="Data Source=Servername;Network Library = DBMSSOCN;Initial Catalog=database;User ID=user;Password=password" providerName="System.Data.SqlClient"/>
</connectionStrings>
into my ConnectionString class.
public class ConnectionString
{
public string DBConn = ConfigurationManager.ConnectionStrings["DBConn"].ToString();
}
in the back end i have a created a form to add new server connection information to add new values to app.config connectionString. SvrConfig form
using System;
using System.Windows.Forms;
using System.Configuration;
using System.Reflection;
namespace B4_HRM_System
{
public partial class SvrConfig : Form
{
public SvrConfig()
{
InitializeComponent();
}
private void btnsave_Click(object sender, EventArgs e)
{
try
{
if (txtserver.Text == "")
{
MessageBox.Show("Please enter Server Name.", "7KProject", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtserver.Focus();
return;
}
if (txtdb.Text == "")
{
MessageBox.Show("Please enter Database.", "7KProject", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtdb.Focus();
return;
}
if (txtuser.Text == "")
{
MessageBox.Show("Please enter Username.", "7KProject", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtuser.Focus();
return;
}
if (txtpass.Text == "")
{
MessageBox.Show("Please enter Password.", "7KProject", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtpass.Focus();
return;
}
string DBConn = "Data Source={0};Initial Catalog={1};User ID={2};Password={3}";
DBConn = string.Format(DBConn, txtserver.Text, txtdb.Text, txtuser.Text, txtpass.Text);
Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
ConnectionStringsSection connSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connSection.ConnectionStrings["DBConn"].ConnectionString = DBConn;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("AppSettings");
MessageBox.Show("Successfully Completed", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnexit_Click(object sender, EventArgs e)
{
this.Hide();
b4login frmb4login = new b4login();
frmb4login.Show();
}
}
}
but every time connectionString is saved i have to restart application. Is there any way or improvement for SvrConfig form when i close it updates/refresh connectionString in app.config file before showing login form so i don't have to restart the application.
Upvotes: 0
Reputation: 122
I suggest using the NuGet package Microsoft Data Connection Dialog. It worked for me.
Upvotes: 0
Reputation: 218798
If you want to edit the values separately, store them separately. Something like this:
public class ConnectionString
{
public string DataSource { get; set; }
public string InitialCatalog { get; set; }
public string UserID { get; set; }
public string Password { get; set; }
public ConnectionString(string dataSource, string initialCatalog, string userID, string password)
{
DataSource = dataSource;
InitialCatalog = initialCatalog;
// etc.
}
public override string ToString()
{
return string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", DataSource, InitialCatalog, UserID, Password);
}
}
Then you can create a ConnectionString
object with the values you want, modify those values however you want, and any time you want the resulting connection string from that object you just call .ToString()
on the instance of the object.
Basically, any time you have a string with multiple values contained therein, resist the temptation to modify the string for manipulating those values. If you have separate values, then you have separate variables. Keep separate things separate. Only build the resulting string when you need it.
Upvotes: 1
Reputation: 13633
You could create a User string Setting:
Properties > Settings:
Name Type Scope Value
MyConnection string User Data Source=TCP/IP,PORT;Initial Catalog=DataBase;User ID=user;Password=*******"
Reading using:
string MyConn = Properties.Settings.Default.MyConnection;
And Saving using:
Properties.Settings.Default.MyConnection = "...";
Properties.Settings.Default.Save();
Unfortunately, the (ConnectionString) type is Application-scope (read-only), so use User-scoped "string" instead. Also if you're going to store password, it'd probably be best to encrypt/decrypt that string.
Upvotes: 0
Reputation: 139
Create a configuration file to store database credentials. When your application starts read the credentials and build a connection string. Store it and use to create a dbContext. Use your form to change the configuration file.
Upvotes: 0
Reputation: 12848
I wouldn't recommend doing it the way you are doing it, but to build on your code, you should use a property not a field in the class.
So update your class this way:
public class ConnectionString
{
public string DBConn { get; set; } = "your default string here";
}
Then somewhere else in your code you can get or set the property like this
var connectionString = new ConnectionString();
var dbConn = connectionString.DBConn; // get the value
connectionString.DBConn = "new string"; // set it with a new value
Upvotes: 0