Dilip Dilip - 4 months ago 16
ASP.NET (C#) Question

How to delete and update records using gridview from an xml file in asp.net

I want to update and delete records by selecting the row of a gridview. This code is for adding the employee details.

protected void Button_Add_Employee_Click(object sender, EventArgs e)
{
XmlDocument xmlEmloyeeDoc = new XmlDocument();
xmlEmloyeeDoc.Load(Server.MapPath("~/Employees.xml"));
XmlElement ParentElement = xmlEmloyeeDoc.CreateElement("Employee");
XmlElement ID = xmlEmloyeeDoc.CreateElement("ID");
ID.InnerText = TextBox_Id.Text;
XmlElement Name = xmlEmloyeeDoc.CreateElement("Name");
Name.InnerText = TextBox_Name.Text;
XmlElement Designation = xmlEmloyeeDoc.CreateElement("Designation");
Designation.InnerText = TextBox_Desig.Text;

ParentElement.AppendChild(ID);
ParentElement.AppendChild(Name);
ParentElement.AppendChild(Designation);

xmlEmloyeeDoc.DocumentElement.AppendChild(ParentElement);
xmlEmloyeeDoc.Save(Server.MapPath("~/Employees.xml"));
BindGrid();
}``

Answer

Just write code like this For Updating: protected void GridView_RowUpdating(object sender, GridViewUpdateEventArgs e) { DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("~/YourXmlFilePath")); int iXmlRow = Convert.ToInt32(Convert.ToString(ViewState["gridrow"])); ds.Tables[0].Rows[iXmlRow ]["Name"] = txtFirstName.Text; ds.Tables[0].Rows[iXmlRow ]["Designation"] = txtLastName.Text; ..... etc ds.WriteXml(Server.MapPath("~/YourXMLPath")); BindGrid(); } For Deleting: protected void GridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("~/YourXmlFilePath")); ds.Tables[0].Rows.RemoveAt(e.RowIndex); ds.WriteXml(Server.MapPath("~/YourXmlFilePath")); BindGrid(); } Hope this help...`