Tasleem Ahmad
Tasleem Ahmad

Reputation: 53

How to use xml with c# form application To get text for Lables Based on user Input from xml file

i'm working on An win form application in c# i wants to add a functionality to my application by which i can change the lable.text on user input basis

i wants to use an xml file so i can set some labels as predefined values that can be changes any time without recompiling application or changing language of my application

i have an xml file that i wants to use in my form application

    <?xml version="1.0" encoding="utf-8" ?>
  <product>
    <product_id>1</product_id>
    <product_name>Product 1</product_name>
    <product_price>1000</product_price>
  </product>
  <product>
    <product_id>2</product_id>
    <product_name>Product 2</product_name>
    <product_price>2000</product_price>
  </product>
  <product>
    <product_id>3</product_id>
    <product_name>Product 3</product_name>
    <product_price>3000</product_price>
  </product>
  <product>
    <product_id>4</product_id>
    <product_name>Product 4</product_name>
    <product_price>4000</product_price>
  </product>

in my application i have some text for textbox1,textbox2 And textbox3 And Lables As Lable1,Lable2,Lable3

on text change in textbox1 I wants to change the value of lable1.text According to id for example if user enters 1 in textbox1 then lable text should be changed to product 1

As beginner in c# and programming don't know how to get this working....

Upvotes: 0

Views: 867

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

You can parse xml with Linq to Xml. On text changed event do the following:

int id;
if (!Int32.TryParse(textbox1.Text, out id))
    return; // do nothing if not integer entered

XDocument xdoc = XDocument.Load(path_to_xml_file);
var product = xdoc.Descendants("product")
                  .FirstOrDefault(p => (int)p.Element("product_id") == id);

lable1.Text = (product == null) ? "" : (string)product.Element("product_name");

BTW when ask question, always provide code which you already have, to show us where you stuck. Also as I commented under question your xml is invalid, because it have several root elements. Wrap all your product elements into some root, like <products>.

Upvotes: 1

Alexandru Lache
Alexandru Lache

Reputation: 479

Consider dividing your problem in reading and writing XML in C# and look for each answer, also for setting you can use the Settings.Settings file and select User or Application if you want the setting to change or not.

Build XML

Read XML XPath

Ream XML XmlReader, single pass

Settings file

Upvotes: 0

Related Questions