0

I have the following code in which I want to change the default database in code behind.

Web.config

<dataConfiguration defaultDatabase="olddatabasename"/>

My code behind

DatabaseSettings dbSettings = (DatabaseSettings)ConfigurationManager.GetSection("dataConfiguration");
dbSettings.DefaultDatabase = "newdatabasename";

But it gives the following error:

The configuration is read only

How can I change this in code behind?

Cœur
  • 37,241
  • 25
  • 195
  • 267
abbas
  • 424
  • 3
  • 10
  • 22
  • You're probably better off storing that in a *separate* configuration mechanism that you can control better. – Robert Harvey Jun 04 '14 at 15:54
  • You might want to store the database and connection string in the registry: http://msdn.microsoft.com/en-us/library/ff649224.aspx – user8128167 Jun 04 '14 at 15:55
  • 1
    I'd just as soon get flogged than to store anything in the registry. Perhaps your own XML file? – Robert Harvey Jun 04 '14 at 15:56
  • So is there no way of achieving this, without the suggestions? – abbas Jun 04 '14 at 15:56
  • Why does it have to be that particular configuration entry? – Robert Harvey Jun 04 '14 at 15:57
  • I have a drodpwn which allows the user to select database from it...so I want to change this based on the selection – abbas Jun 04 '14 at 15:58
  • Yes, but you can store the value of that dropdown anywhere. – Robert Harvey Jun 04 '14 at 15:59
  • Yes, but the dropdown has the list of databases.When the user selects the list of database name I want to change this dafault database so all calls to database are made to the selected database. – abbas Jun 04 '14 at 16:01
  • this may be what you are looking for: http://stackoverflow.com/questions/2260317/change-a-web-config-programmatically-with-c-sharp-net http://stackoverflow.com/questions/360024/how-do-i-set-a-connection-string-config-programatically-in-net – Audor Jun 04 '14 at 16:10

1 Answers1

0

Using the link by @Audor from comments I was able to fix the issue:

var settings = ConfigurationManager.GetSection("dataConfiguration");
var fi = typeof(ConfigurationElement).GetField("_bReadOnly", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
fi.SetValue(settings, false);
DatabaseSettings dbSettings = (DatabaseSettings)ConfigurationManager.GetSection("dataConfiguration");
dbSettings.DefaultDatabase = databseName;
abbas
  • 424
  • 3
  • 10
  • 22