Tutorial :add contents through textboxes



Question:

I have a Windows Forms application which contain a textbox (tbox) and two buttons: Save (b1) and Delete (b2) and an XML file leaf.xml

Whenever i am putting anything in textbox and then click Save (b1) the content in textbox will be saved in the leaf.xml file. When i press delete (b2), it will delete from the file leaf.xml and at the same time it will disable the Save button.

this is the xml file wahatever adding will come to tag,suppose if we add test it will come as

<Name>test</Name>


Solution:1

You probably want to look at the XMLSerializer. It will let you serialize/deserialize your "ObjectClass" to/from a stream. Likewise, you probably want to look at the File class, for opening file streams (to pass into the XMLSerializer) and delete files (File.Delete).


Solution:2

Use LINQ to do that....see code below:

XDocument xmlDoc = XDocument.Load(Server.MapPath("People.xml"));    xmlDoc.Element("Persons").Add(new XElement("Person", new XElement("Name", txtName.Text),  new XElement("City", txtCity.Text), new XElement("Age", txtAge.Text)));    xmlDoc.Save(Server.MapPath("People.xml"));  lblStatus.Text = "Data successfully added to XML file.";  


Solution:3

The save should be something like this, the delete works with XPath (find the Name element that has the supplied text in it, then delete it, save the file again.)

This will not work if any person with the same name is entered off course...

Save_Click(object sender, EventArgs e)  {    FileStream fs = new FileStream("leaf.xml",FileMode.Open,FileAccess.Read, FileShare.ReadWrite);    XmlDocument doc = new XmlDocument();    doc.Load(fs);    XmlElement elem = doc.CreateElement("","Name","");    XmlText text = doc.CreateTextNode(textbox1.Text);    elem.AppendChild(text);    doc.RootNode.AppendChild(elem);      doc.Save("leaf.xml");  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »