This question is asked many times on www.asp.net forums. Although its not a good idea to dynamically write anything in the web.config file reason being that writing anything in web.config will restart the application.
Anyway, if for some reason you don't care about the restart and really wanted this functionality than you can look into this code:
private void GetConfigSettings()
{
string path = Server.MapPath("Web.config");
string newConnectionString = @"Server=local;Database="+txtDatabaseName.Text+";Trusted_Connection=true";
XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
XmlNodeList nodeList = xDoc.GetElementsByTagName("appSettings");
XmlNodeList nodeAppSettings = nodeList[0].ChildNodes;
XmlAttributeCollection xmlAttCollection = nodeAppSettings[0].Attributes;
xmlAttCollection[0].InnerXml = txtKey.Text; // for key attribute
xmlAttCollection[1].InnerXml = newConnectionString; // for value attribute
xDoc.Save(path); // saves the web.config file
}