I defind the connection string in web.config
<ConnectionStrings>
<add name="student" connectionString="Server=student;Max Pool Size=300;Initial Catalog=studentDB;User ID=student;Password=st123dent;" providerName="System.Data.SqlClient"/>
</Connectionstrings>
how can i change the connection string dynamically in c#
in Web Confige put this code
in your connection put this code
If a user is able to change the value of the Setting, then the web.config file is the wrong place to store the setting.
You should check out a User Scoped value in a Settings file instead.
MSDN - Using Settings in C
When using settings like this, changing the value at runtime is easy:
You can open your Web.Config file for reading and writing using
WebConfigurationManager.OpenWebConfiguration
orWebConfigurationManager.OpenMappedWebConfiguration
. And provided you have write permission you'll be able to make modifications such as changing the connection string.This surely has to be better than using reflection to modify a private field.
Modifying web.config will then recycle the web application, so this isn't suitable for letting users make changes to web.config - though it could be used in specific scenarios such as deployment.
Example:
Configuration is read only so you can not do it in obvious way like
This raises System.Configuration.ConfigurationErrorsException exception which saying that "Configuration is read only".
Here is a trick using reflection to reset readOnly attribute of configuration element. See this article for full details Programmatically setting a connectionString property
Code snippet:
BTW, why you need change it the configuration? I'm feeling that you'are trying to solve some problem in wrong way.
Use NameSpace