In this article, I will show you how to adding connection string in web config, via dynamically in asp.net c#. You can also change connection string in web config configuration file.
The following function has the WebConfigurationManager, it opens the web.config file in the asp.net application. For dynamically adding connection string, you need to check for key and value field. If the connection string is not there, you need to a create new connection string otherwise it updates the value of connection string.
Desgin page:
<form id="form1" runat="server">
<div style="border:1px solid #e1d8d8;height:350px;width:500px">
<h2>Dynamically change/Update Connection string in asp.net </h2>
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Upload Image" OnClick="btnUpdate_Click" />
</div>
</form>
Code behind:
protected void btnUpdate_Click(object sender, EventArgs e)
{
UpdateConnectionString("testconn", "admin");
}
public void UpdateConnectionString(string key, string value)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
if (config.ConnectionStrings.ConnectionStrings[key] == null)
{
config.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(key,value));
}
else
{
config.ConnectionStrings.ConnectionStrings[key].ConnectionString =value;
}
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
Post your comments / questions
Recent Article
- How to get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
- urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0
Related Article