0

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....

Tasleem Ahmad
  • 53
  • 1
  • 1
  • 10
  • And what have you tried so far ? [**Here a kickstart**](http://www.google.com/search?btnG=1&pws=0&q=c%23+read+xml+site%3Astackoverflow.com) The second result goes straight for a good start by reading a XML file. – Prix Jul 02 '13 at 18:13
  • Your xml does not have single root element, so it is not valid. What you tried? – Sergey Berezovskiy Jul 02 '13 at 18:27

2 Answers2

1

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>.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
0

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

Community
  • 1
  • 1
Alexandru Lache
  • 477
  • 2
  • 14