Good day. The following problem arose, there is an XML file, I manage to read it and write data to the ComboBox, I would like that when I selected the required value in "Combobox" -e, not all nodes were displayed at once, but only in order. That is, if the attribute with the value "Bill Gates" is selected in the "combobox" -e, then the company and age of this particular node were displayed in the GridView. And I get everything at once ...

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { dataSet1.ReadXml(@"F:\XML1.xml"); dataGridView1.DataSource = dataSet1; dataGridView1.DataMember = "operation"; } private void button2_Click(object sender, EventArgs e) { XmlDocument doc = new XmlDocument(); doc.Load(@"F:\XML1.xml"); XmlElement element = doc.DocumentElement; foreach (XmlNode xml in element.SelectNodes("//Путь/путь")) { foreach (XmlNode child in xml.ChildNodes) { if (child.Name == "operation") { XmlNode Att = child.Attributes.GetNamedItem("info"); comboBox1.Items.Add(Att.Value); } } } } 

XML example:

 <?xml version="1.0" encoding="utf-8" ?> <users> <user name="Bill Gates" info="2"> <company>Microsoft</company> <age>48</age> </user> <user name="Larry Page" info="3"> <company>Google</company> <age>42</age> </user> 

    2 answers 2

    Try using the Select method of DataTable.

    With it, you can select the desired items.

    PS In my opinion it is irrational for every new combo box to load new data into a DataTable.

    It is better to read them once in a class property, and then use them.

    • Can show a code sample, I about a class. - Tibomso
    • Well, you can create a property at the form level with the DataSet type. In the constructor, you do a read into this DataSet and you no longer need to read the same thing 100 times. Then in the event handler you work with this variable. Perhaps you can and make more beautiful. - iluxa1810

    Found a solution:

     private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { var path = @"F:\XML1.xml"; var doc = XElement.Load(path); var item = doc.Descendants("operation").Where(el => el.Attribute("info").Value == comboBox1.Text).Select(n => new { Company = n.Element("oper_number").Value, Age = n.Element("oper_name").Value }).FirstOrDefault(); MessageBox.Show(string.Format("Company: {0}, Age: {1}", item.Company, item.Age), "Result"); }