c# - 根据以前的 XML 组合框选择填充组合框

标签 c# xml winforms c#-4.0 combobox

我是 .net 初学者。我正在阅读 XML file并在两个组合框中显示它,即 cbProductcbBrandName

我需要根据 cbProduct 中的选定文本在 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 == "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<string>()); // 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<string>()); // Then convert that into a string[]

有用吗?当我自己编写代码时,我喜欢将长 LINQ 语句拆分成这样,将它们放在不同的行中,然后我可以只读下面的行:“我得到一个列表,如果这是真的,然后根据其他内容选择在它上面,然后把它变成一个数组。”

关于c# - 根据以前的 XML 组合框选择填充组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12757461/

相关文章:

c# - 如何注入(inject)与 Moq 一起使用的模拟程序集

XML 查询,通过在 BaseX 中导致错误 "Item expected, sequence found"进行排序

c# - 我可以在透明的 WinForm 上绘制面板吗?

javascript - 如何使用javascript获取xml中某个标题的内容?

c# - 将用户控件从解决方案资源管理器添加到 winform

C# - 获取 ToolStripMenuItem 的父项

c# - 如何将 SecureString 转换为 System.String?

c# - 从句子列表中获取最长公共(public)子字符串

c# - 如何在表格上画一个覆盖整个工作区域的圆?

android - 当内部 View 与父级右对齐时,RelativeLayout 背景会拉伸(stretch)