Friday, 25 November 2011

Programmatically configure the connection string of the Dataset.

Technologies used: Microsoft Visual Studio, c#.

The conditions are:
1) We have a MS Visual Studio project. The DataSet with tables drag'n'dropped on it. The tables were dropped from server explorer.
2) When dataset was initialized Settings.settings file was created. The DB Connection string is stored in it.
3) We need to change the value of the connection string programmatically when the application is run.
4) Main difficulty is that ConnectionString property of Settings class has no setter. Which means we can not set it - only manually from the settings designer.

The salvation solution is:
1) Create class in the Properties folder of the project. Name it for example Settings.Override.cs.
2) Class should extend Settings class. It is easy to do since Settings class is partial one. So the new class should be defined like following: partial class Settings (inside the Settings.Override.cs file)
3) Create a setter property in the new class:
        public string GgstatisticsConnectionString
        {
            set { this["ggstatisticsConnectionString"] = value; }//the name of the connection string in the Settings.
        }
4) In the beginning of the program (in some kind of initialization section) initialize the connections string:
Settings.Default.GgstatisticsConnectionString = "POLETIM-PC\POLETIMSERVER;Trusted_Connection=yes;database=statisticsdb; connection timeout=0";
5) Now the dataset will use the set connection string when it will be initialized.
??????????
6) PROFIT


No comments:

Post a Comment