【问题标题】:how to get xml data to listbox如何获取xml数据到列表框
【发布时间】:2013-05-03 15:18:17
【问题描述】:

我在将数据从 xml 文件获取到列表框时遇到了问题。

这是我想在列表框中获取的数据:

<gjester>
  <gjest>
    <id>test</id>
     <fornanv>test</fornanv>
     <etternavn>test</etternavn>
     <adresse>test</adresse>
     <telefonnr>test</telefonnr>
  </gjest>
</gjester> 

我在我的 gui 中创建了一个列表框。但我不知道在我的代码中写什么。

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)

{
 I don't know what to write here
}

【问题讨论】:

标签: c# xml listbox


【解决方案1】:

大约有无数种方法可以将 XML 文件中的项目添加到列表框中,但一个很好的起点是 XMLTextReader 类和 ListBox.Items.Add() 方法的 MSDN 文档。

此外,您可能希望在列表框上的 SelectedIndexChanged 事件以外的地方执行此操作。出于学习目的,请单击按钮进行尝试。

祝你好运 - 在查看上述内容后,如果你还没有弄清楚,我相信有人会帮助你。

【讨论】:

    【解决方案2】:

    这是 .NET 4.0 (VS2010 C#),完全未经测试,但可以让您开始......

    private void FillListBoxWithThingsIWantToSelect()
    {
           XDocument ListBoxOptions = XDocument.Load(Filename);
            foreach (XElement element in ListBoxOptions.Root.Elements())
            {  
            if (element.Name.LocalName.Contains("gjester"))
                {
                foreach (XElement subelement in element.Elements())
                   {
                   if (subelement.Name.LocalName.Contains("gjest"))
                       {
                       // What do you want to add? The Attribute? Element value
                        listbox1.Items.Add(element.Value.ToString());
                       } 
                   }   
                }
            }
    }
    

    如果您在列表框中列出了您的平台和您想要的内容,将会有所帮助。 你想从你的构造函数中调用它。

    【讨论】:

      【解决方案3】:

      可以使用字典对象将数据从 XML 绑定到 Listbox。

      var dic = (from order in ds.Tables[0].AsEnumerable()
                         select new
                         {
                             UserView = order.Field<String>("Value"),
                             DevView = order.Field<String>("id")
      
                         }).AsEnumerable().ToDictionary(k => k.DevView, v => v.UserView);
      

      点击here for reference

      【讨论】:

      • 这没有回答问题。
      • 重要的是,当你喜欢绑定数据时,希望它的确切答案..不能写每一行代码来表达你的答案,只能导航想法
      • Read here 了解如何写出好的答案。
      猜你喜欢
      • 2018-09-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多