Wednesday, August 05, 2009

Settings DataSet/TableAdapter Connection Strings at Runtime

The DataSet's TableAdapter generates strongly types classes in VS.NET, with properties to connection strings that are read-only at runtime, unless, of course, you choose the "User" scope. Follow these steps for changing the connection string upon application startup:
  1. Open up the Settings.settings file, whatever it might be named in your project. If it's not there, create one by a) adding a new Settings file to your project, b) adding a new (Connection string) setting, c) save it, d) then ensure that each DataSet's TableAdapter's Connection property references this Settings file's (Connection string) setting.
  2. Press the F7 key to view its code.
  3. Add the following code to the Settings() constructor: this.SettingsLoaded += new System.Configuration.SettingsLoadedEventHandler(Settings_SettingsLoaded);
  4. Add the following method to the Settings class: private void Settings_SettingsLoaded(object sender, System.Configuration.SettingsLoadedEventArgs e) { try { Settings.Default["PrizeWinsConnectionString"] = "PUT YOUR CONNECTION STRING HERE!"; } catch (System.Exception err) { throw; } }
  5. Save and recompile your project/solution.


kulveer said...

I wonder whether is not same as before where you read the config file values. Is there any change.

Anonymous said...

Thank You. I've been banging my head on a wall all weekend looking for a solution. You are the man. It worked like a champ.

Android app developers said...

I like your blog analyze.This is one of the good application.Nice to read about your post.Supper.