基于XML中先前的combobox选择填充combobox
我是.net初学者。 我正在读取一个XML文件 ,并在两个combobox中显示它,即。, cbProduct
和cbBrandName
我需要在cbBrandName
显示关于cbBrandName
中所选文本的文本。
我实现了以下代码:
DataSet ds = new DataSet(); ds.ReadXml(@"..\..\stock.xml"); cbProduct.DataSource = ds.Tables[0].DefaultView.ToTable(true, "productname"); cbProduct.DisplayMember = "productname"; cbBrandName.DataSource = ds.Tables[0].DefaultView.ToTable(true, "brandname"); cbBrandName.DisplayMember = "brandname";
上面的代码显示了cbBrandName
所有文本值。 如何使其仅显示链接到cbProduct
中xml文件的选定“productname”列的文本值。
请帮忙。
提前致谢。
LINQ看起来比它更可怕。 在Anirudha的答案中使用了两个部分,我将尝试解释。 第一个是.Select(x=>
。这意味着“对于列表中的每个东西,用一些东西替换它。”x表示列表中的每个项目。
例如:
new string[]{"a", "b", "c"}.Select(x=>x.ToUpper());
将{“a”,“b”,“c”}的数组转换为{“A”,“B”,“C”}的数组。 它只是说“取出列表中的每一个东西,并通过调用ToUpper()
取而代之。
LINQ的另一位是.Where(x=>
。这只是说“给我一个更小的列表,只有这个陈述是真的”。所以
new string[]{"a", "b", "c"}.Where(x=>x == "a");
会给你一个{“a”}的清单。 用x != "b"
替换x == "a"
x != "b"
将为您提供{“a”,“c”}的列表。 因此,在第二部分代码中,您说“在我用我的产品名替换每个项目之前,我想过滤掉任何与我想要匹配的内容不相符的内容。然后我转换剩下的内容。 “
要将这些应用于代码示例,我将重新格式化行并对其进行注释。
// To set the first combo box: cbProduct.Items.AddRange( // Add everything we produce from this to the cbProduct list doc.Descendants("items") // For each thing that represents an "items" tag and it's subtags .Select(x=>x.Element("productname").Value) // Transform it by getting the "productname" element and reading it's Value. .ToArray()); // Then convert that into a string[]. // To set the second combo box: string product2Search=cbProduct.SelectedItem.ToString();// get the currently selected value of cbProduct. cbBrandName.Items.Clear(); //clears all items in cbBrandNamedoc cbBrandName.Items.AddRange( // Add everything we produce from this to the cbBrandName list doc.Descendants("items") // For each thing that represents an "items" tag and it's subtags .Where(x=>x.Element("productname").Value==product2Search) // Filter our list to only those things where the productname matches what's currently selected in cbProduct (which we just stored) .Select(y=>y.Element("brandname").Value) // Transform it by getting the "brandname" element and reading it's Value. .ToArray ()); // Then convert that into a string[]
这有用吗? 当我自己编写代码时,我喜欢通过将它们放在像这样的单独行来分割长LINQ语句,然后我就可以读下这些行:“我得到一个列表,这是真的,然后选择另一个基于它的东西在它上面,把它变成ARRAY。“
在LINQ2XML中
XElement doc=XElement.Load(@"..\..\stock.xml"); //put this code in the form_load event cbProduct.Items.AddRange(doc.Descendants("items").Select(x=>x.Element("productname").Value).ToArray());//adds all products //put this code in the SelectedIndexChanged event of cbProduct string product2Search=cbProduct.SelectedItem.ToString();//selected value of cbProduct cbBrandNamedoc.Items.Clear(); //clears all items in cbBrandNamedoc cbBrandNamedoc.Items.AddRange(doc.Descendants("items").Where(x=>x.Element("productname").Value==product2Search).Select(y=>y.Element("brandname").Value).ToArray ());