简体   繁体   English

C#使用基于另一个组合框的XML数据填充组合框

[英]C# populate combobox with XML data based on another combobox

Total noob when it comes to XML here, I've got an XML file with the structure as follows: 在这里涉及XML的时候,我已经有了一个XML文件,其结构如下:

<Error_Codes>
   <Test_1>
     <Code>ABC</Code>
     <Description>Item #1</Description>
   </Test_1>
   <Test_1>
     <Code>DEF</Code>
     <Description>Item #2</Description>
   </Test_1>
   <Test_2>
     <Code>UVW</Code>
     <Description>Item #3</Description>
   </Test_2>
   <Test_2>
     <Code>XYZ</Code>
     <Description>Item #4</Description>
   </Test_2>

What I want to do is have the user select either Test 1 or Test 2 from a previous ComboBox, then populate the 2nd ComboBox (let's call it codeCBO) with the values in the <Test 1> portion of the XML file, ideally with each item in codeCBO structured like Code-Description . 我想要做的是让用户从先前的ComboBox中选择Test 1或Test 2,然后使用XML文件的<Test 1>部分中的值填充第二个ComboBox(我们称其为codeCBO),最好是每个类似于Code-Description codeCBO中的项目。 I looked online and see there are a lot of XML tutorials, but I don't see anything like what I'm trying to do. 我在网上看了看,看到有很多XML教程,但是看不到我要尝试的东西。 Any help/advice would be much appreciated. 任何帮助/建议将不胜感激。

For some reason the Error_codes end tag does not show up here, but it is in the XML file I'm working with 由于某种原因,Error_codes结束标记未在此处显示,但在我正在使用的XML文件中

After messing with this for 3 days, I finally found the solution that worked for me. 经过三天的摸索,我终于找到了适合我的解决方案。 XML file now looks like this: XML文件现在看起来像这样:

<Error_Codes>
   <Test1 code="0001" description="test ABC"/>
   <Test1 code="0002" description="test DEF"/>
   <Test2 code="9999" description="test UVW"/>
   <Test2 code="8888" description="test XYZ"/>
</Error_Codes>

Then, my C# code looks like this: 然后,我的C#代码如下所示:

 private void stationCBO_SelectedIndexChanged(object sender, EventArgs e)
 {
     codeCBO.Items.Clear();
     LoadXML(stationCBO.Text);
 }

private void LoadXML(string station)
    {
        XmlReader reader = XmlReader.Create("Failure_Modes.xml");

        while (reader.Read())
        {
            if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == station))
            {
                if (reader.HasAttributes)
                {
                    string text = reader.GetAttribute("code") + "-" + reader.GetAttribute("description");
                    codeCBO.Items.Add(text);
                }
            }

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM