Connection String in app.config

blounty

Member
Joined
Aug 21, 2007
Messages
19
Location
Nottingham, England
Programming Experience
1-3
Hi all,

I need to be abble to modify the connection string which is stored in the application settings. you cannot do this through my.settings as it is read only.
Is there any way of accessing this and setting it to something else?

Thank you for looking.

Regards

Alex.
 
yes there is, but it is completely horrible!!

You can copy the connection string that is in the app settings (just highlight what is shown in Value and then copy).

Change the Type to String, and the Scope to User. Delete what is put in as Value and then paste back your "original" connection string.

Make a note of the Name. (i.e. it will be something like ProjectConnectionString) - you can change this if you want to.


To simply change the connection string, use

VB.NET:
My.Settings.ProjectConnectionString = "Put your connection string here"

NOTE!!!! Right... now for that "horrible" bit!
Whilst you have it set as User and String, DO NOT MAKE ANY CHANGES TO ANY TABLE-ADAPTER. If you try to, you'll get an error. Close everything down AND DO NOT SAVE ANYTHING! You will have to come completely out of VS, lose any changes you've made and reopen your project.

if you should need to make changes to any of your table adapters (such as adding a new query etc), go back into the settings, and change Scope to Application and then Type to (ConnectionString)
Make sure that the connection string is right, and then press "Synchronise" button that is on that page.
Save the changes first, and then you will be able to edit your tables.

2nd Note!! Now you won't be able to run your app because My.Settings.ProjectConnectionString will need commenting out first.

Once you are happy with the changes made to your tables, you can go back and edit the Settings to the User String, repaste your connection string, Synchronise, uncomment the My.Settings.ProjectConnectionString lines you have entered and run your application :D

...that's all there is to it ;)

PS - I do this myself. I have one application shared to users in 3 countries, and I have set it so each country has it's own database. Therefore I set the connection string to the correct country DB when the project is opened by matching the logged on user to their country.
 
Actually, editing settings with Application scope is waaaaaayyyyyyy easier than that. You call ConfigurationManager.OpenExeConfiguration to get a Configuration object that represents your config file. Edit the bits you want then call the Save method of the Configuration object. You can then call ConfogurationManager.RefreshSection to force the new value(s) to be loaded into your application.
 
Back
Top