How to read XML element and display the data in TextBox using C#


I saw many people asking this query in forums. So I though I will share how this can be achieved in simple method. Below is the C# code to Read XML element and display those data in corresponding TextBox.

C# code to Read XML element and display the data in TextBox

There are many ways to read XML element, but here I am going to explain you a simple C# code to read XML and how this can be achieved using very few lines of code.

You need to pass ID to below function to display corresponding data in textboxes. This id should be unique in order to display the data in textbox.

What this code does is, first it will read complete XML file and keep the value in a DataSet, then we iterate through the DataSet to find the exact match of the ID and display the matching data in corresponding TextBoxes.


private void PopulateXMLData(string Empid)
{
try
{
string XMLFilePath = System.Configuration.ConfigurationManager.AppSettings["XMLFileDetails"];//add an entry in web.coinfig for XML file path.
DataSet ds = new DataSet();
ds.ReadXml(XMLFilePath);

foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["Employeeid"].ToString()) == Empid.ToString())
{
txtName.Text = dr["Name"].ToString().Trim();
txtAddress.Text = dr["Address"].ToString().Trim();
txtPhone.Text = dr["Phone"].ToString().Trim();
//Continue for all fields....
}
}
}
catch (Exception ex)
{
lblMsg.Text = "Error while fetching the record" + ex.Message;
}


Please post your comments if you have any doubts about this code.


Article by Asheej T K
Thanks and Regards Asheej T K Dotnet Galaxy

Follow Asheej T K or read 33 articles authored by Asheej T K

Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: