【问题标题】:filling listbox with textfile用文本文件填充列表框
【发布时间】:2023-03-20 02:20:02
【问题描述】:

所以我试图用我放入 txt 文件的名称填充列表框。 当我使用 Console.WriteLine(naam) 时,它实际上显示了文件中的名称,但我无法将它们放入列表框中。有谁知道这个问题的解决方案?谢谢你的到来。

public void PopulateList( ListBox list, string file)
{
        string naam;
        string sourcepath =  Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
        string myfile = System.IO.Path.Combine(sourcepath, file);
        StreamReader reader = File.OpenText(myfile);
        naam = reader.ReadLine();
        while (naam != null)
        {
            list.Items.Add(naam);
            list.Items.Add(Environment.NewLine);
            naam = reader.ReadLine();
        }
        reader.Close();
}

【问题讨论】:

  • 感谢您的帮助,我找到了解决方案,这只是一个愚蠢的错误..

标签: c# wpf listbox streamreader


【解决方案1】:

首先请使用 MVVM 开发任何 wpf 应用程序。像这样在后面的代码中操作 UI 控件并不好。使用适当的绑定。

如果我必须解决这个问题,我会创建像这样的字符串集合

 public ObservableCollection<string> Names { get; set; }

并像

一样将其绑定到 ListBox
 <ListBox x:Name="NamesListBox" ItemsSource="{Binding Names}"/>

然后在我的 Window 的构造函数中,我将初始化 Names 并设置 Window 的 DataContext 并更新 PopulateList 方法,如下所示:

    public MainWindow()
    {
        InitializeComponent();
        Names = new ObservableCollection<string>();
        DataContext = this;
        PopulateList("C:\names.txt");
    }

    public void PopulateList(string file)
    {
        string naam;
        string sourcepath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string myfile = System.IO.Path.Combine(sourcepath, file);
        StreamReader reader = File.OpenText(myfile);
        naam = reader.ReadLine();
        while (naam != null)
        {
            Names.Add(naam);
            naam = reader.ReadLine();
        }
        reader.Close();
    }

【讨论】:

    【解决方案2】:

    看看this

    StreamReader sr = new StreamReader("youfilePath");
    string line = string.Empty;
    try
    {
        //Read the first line of text
        line = sr.ReadLine();
        //Continue to read until you reach end of file
        while (line != null)
        {
            list.Items.Add(line);
            //Read the next line
            line = sr.ReadLine();
        }
    
        //close the file
        sr.Close();
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message.ToString());
    }
    finally
    {
        //close the file
        sr.Close();
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用File.ReadLines 来使它更好一点:

      string sourcepath =  Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
      string myfile = Path.Combine(sourcepath, file);
      
      var items = File.ReadAllLines(myfile)
          .Select(line => new ListItem(line));
      
      List.Items.AddRange(items);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-18
        • 1970-01-01
        相关资源
        最近更新 更多