Add Key and Values to the Web.config File Dynamically in ASP.NET

This article will help you add the Key and Value to the web.config file dynamically.

This is simple and useful application for those who wants dynamic changes in the web.config file. The sample source code allows you to change the key and value pair. There is
no need to open web.config file. The application also allows you to update and delete the key/value pair.

Before you start any operation, you need to select one of the option buttons - Add, Update, or Delete.

Let's have to UI design Home Page.

Step 1:

The UI for adding a new key/value looks like following:



For updating the previous tag, Just select the Key values from Dropdown and update the new values with previous one



For Delete Operation, select the Key from dropdown which you want delete.







Step 2:

Please find the Code (.cs)

  1. protected void Add_values(object sender, EventArgs e)  
  2. {  
  3.      if (TextBox1.Text == string.Empty && TextBox2.Text==string.Empty)  
  4.      {  
  5.            //RFC Added  
  6.      }  
  7.      else  
  8.      {  
  9.           string Key_c = TextBox1.Text.ToString().Trim();  
  10.           string Value_c = TextBox2.Text.ToString().Trim();  
  11.           Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");  
  12.           webConfigApp.AppSettings.Settings.Add(Key_c, Value_c);  
  13.           webConfigApp.Save();  
  14.           DisplayConfigTags();  
  15.           Label1.Visible = true;  
  16.           Response.Redirect("Default.aspx");  
  17.      }  
  18. }  
  19.   
  20. protected void update_values(object sender, EventArgs e)  
  21. {  
  22.      Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");  
  23.      string Key_c = KeyList1.SelectedItem.Value;  
  24.      string Value_c = TextBox2.Text.ToString();  
  25.      webConfigApp.AppSettings.Settings[Key_c].Value = Value_c;  
  26.      webConfigApp.Save();  
  27.      Label1.Visible = true;  
  28.      Response.Redirect("Default.aspx");  
  29.      TextBox2.Text = string.Empty;  
  30. }  
  31. protected void detele_values(object sender, EventArgs e)  
  32. {  
  33.      string Key_c = KeyList1.SelectedItem.Value;  
  34.      string Value_c = TextBox2.Text.ToString();  
  35.      Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");  
  36.      webConfigApp.AppSettings.Settings.Remove(Key_c);  
  37.      webConfigApp.Save();  
  38.      Label1.Visible = true;  
  39.      Response.Redirect("Default.aspx");  
  40. }  

Download the attached source code for more details.

Up Next
    Ebook Download
    View all
    Learn
    View all