In this article, you will learn how to change a database name dynamically in a Web.config file in ASP.NET.
Step 1
Open Visual Studio and create a New Project, change the project name to Databasechange.
Step 2
Add a new item to the project.
Step 3
Add new web form and rename it as Databsechnge.
Step 4
Add Bootstrap References in the page and add a Dropdownlist and a button in the page.
Code Snippet
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="databasechnge.aspx.cs" Inherits="Databasechange.databasechnge" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <meta name="viewport" content="width=device-width, initial-scale=1" />
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div class="col-md-4 col-md-offset-4" style="margin-top: 40px">
- <div class="login-panel panel panel-default">
-
- <div class="panel-heading" style="background-color: lightgreen">
- <h3 class="panel-title" style="text-align: center">Change Database in Web.config</h3>
- </div>
- <div class="panel-body">
- <div class="form-group">
- <asp:DropDownList ID="DropDownList1" runat="server" CssClass="form-control">
- <asp:ListItem>Select Database</asp:ListItem>
- </asp:DropDownList>
- </div>
- <div class="form-group">
- <asp:Button ID="Button1" runat="server" Text="Change Database" OnClick="Button1_Click" CssClass="btn-block" />
- </div>
- </div>
- </div>
- </div>
- </form>
- </body>
- </html>
Step 5
Now, Right click on the page and click on View Code and add the following code to bind the dropdown with all databases available on a given server.
- private void FillDropDown()
- {
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConctionString"].ToString()))
- {
-
- SqlCommand cmd = new SqlCommand("SELECT name FROM sys.sysdatabases", con);
- con.Open();
- SqlDataReader dr = cmd.ExecuteReader();
- if (dr != null)
- {
- while (dr.Read())
- DropDownList1.Items.Add(dr.GetString(0));
- }
- }
- }
Step 6
Now, call the FillDropDown()on page load events.
- protected void Page_Load(object sender, EventArgs e)
- {
- FillDropDown();
- }
Step 7
Now, we add a function Changedatabasename and add the following code to this function.
- private void Changedatabasename(string name)
- {
- bool isbool = false;
- string path = Server.MapPath("~/Web.Config");
- XmlDocument doc = new XmlDocument();
- doc.Load(path);
- XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
- XmlNode node;
- isbool = list.Count == 0;
- if (isbool)
- {
- node = doc.CreateNode(XmlNodeType.Element, "add", null);
- XmlAttribute attribute = doc.CreateAttribute("name");
- attribute.Value = name;
- node.Attributes.Append(attribute);
-
- attribute = doc.CreateAttribute("connectionString");
- attribute.Value = "";
- node.Attributes.Append(attribute);
-
- attribute = doc.CreateAttribute("providerName");
- attribute.Value = "System.Data.SqlClient";
- node.Attributes.Append(attribute);
- }
- else
- {
- node = list[0];
- }
- string ConctionString = node.Attributes["connectionString"].Value;
- SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(ConctionString);
- conStringBuilder.InitialCatalog = DropDownList1.SelectedValue;
- node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
- if (isbool)
- {
- doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
- }
- doc.Save(path);
- }
Step 8
Now, call the method Changedatabasename() on clicking button1.
- protected void Button1_Click(object sender, EventArgs e)
- {
- Changedatabasename("ConctionString");
-
- }
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Xml;
-
- namespace WebApplication4
- {
- public partial class WebForm1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- FillDropDown();
- }
- private void FillDropDown()
- {
- using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConctionString"].ToString()))
- {
-
- SqlCommand cmd = new SqlCommand("SELECT name FROM sys.sysdatabases", con);
- con.Open();
- SqlDataReader dr = cmd.ExecuteReader();
- if (dr != null)
- {
- while (dr.Read())
- DropDownList1.Items.Add(dr.GetString(0));
- }
- }
- }
- private void Changedatabasename(string name)
- {
- bool isbool = false;
- string path = Server.MapPath("~/Web.Config");
- XmlDocument doc = new XmlDocument();
- doc.Load(path);
- XmlNodeList list = doc.DocumentElement.SelectNodes(string.Format("connectionStrings/add[@name='{0}']", name));
- XmlNode node;
- isbool = list.Count == 0;
- if (isbool)
- {
- node = doc.CreateNode(XmlNodeType.Element, "add", null);
- XmlAttribute attribute = doc.CreateAttribute("name");
- attribute.Value = name;
- node.Attributes.Append(attribute);
-
- attribute = doc.CreateAttribute("connectionString");
- attribute.Value = "";
- node.Attributes.Append(attribute);
-
- attribute = doc.CreateAttribute("providerName");
- attribute.Value = "System.Data.SqlClient";
- node.Attributes.Append(attribute);
- }
- else
- {
- node = list[0];
- }
- string ConctionString = node.Attributes["connectionString"].Value;
- SqlConnectionStringBuilder conStringBuilder = new SqlConnectionStringBuilder(ConctionString);
- conStringBuilder.InitialCatalog = DropDownList1.SelectedValue;
- node.Attributes["connectionString"].Value = conStringBuilder.ConnectionString;
- if (isbool)
- {
- doc.DocumentElement.SelectNodes("connectionStrings")[0].AppendChild(node);
- }
- doc.Save(path);
- }
-
-
-
- protected void Button1_Click(object sender, EventArgs e)
- {
- Changedatabasename("ConctionString");
-
- }
- }
- }
Step 9
Now, run the project
Step 10
Select Database in DropDown and click on the button.
Step 11
Choose a database and click on the button.
Step 12
Check the connection string and check database name, it's successfully changed.