简体   繁体   English

从文本文件读取并使用Button填充到Listbox

[英]Reading from text file and populate to Listbox with Button

I am trying to create a window program where the program reads from a text file and display the data in a listbox. 我正在尝试创建一个窗口程序,该程序将从文本文件读取并在列表框中显示数据。 I have tried the below coding but the problem now is that every time I click on the button, it will append and the data will repeat. 我已经尝试了下面的编码,但是现在的问题是,每当我单击按钮时,它将追加并重复数据。

How do I do it so that it reads the file and only include new input data? 我该如何做才能读取文件并仅包含新的输入数据?

private void Button_Click(object sender, RoutedEventArgs e)
{
    using (StreamReader sr = new StreamReader("C:\\Users\\jason\\Desktop\\Outbound.txt"))
    {
        string line;
        // Read and display lines from the file until the end of  
        // the file is reached. 
        while ((line = sr.ReadLine()) != null)
        {
            Listbox1.Items.Add(line);
        }
        sr.Close();
    }
}

The probably most simple way to do what you want is to read all lines from the file into a collection, and then assign that collection to the ItemsSource property of your ListBox: 做您想做的最简单的方法是将文件中的所有行读入一个集合,然后将该集合分配给ListBox的ItemsSource属性:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Listbox1.ItemsSource = File.ReadAllLines(@"C:\Users\jason\Desktop\Outbound.txt");
}

As Clemens said in comment, you can either Listbox1.Items.Clear() or Listbox1.ItemsSource = File.ReadAllLines(@"C:\\Users\\jason\\Desktop\\Outbound.txt"); 正如Clemens在评论中所说,您可以使用Listbox1.Items.Clear()Listbox1.ItemsSource = File.ReadAllLines(@"C:\\Users\\jason\\Desktop\\Outbound.txt");
But this would always replace all your listbox with the file. 但这总是会用文件替换所有列表框。 If you just want, as you said, to enter new data, you could simply check if if(!Listbox1.Items.Contains(line)) before adding the item. 如您所说,如果您只是想输入新数据,则可以在添加项目之前简单地检查if(!Listbox1.Items.Contains(line))
Depends on what you really want, reupdate the whole list or just add new entries and not removing old ones. 根据您的实际需求, 重新更新整个列表,仅添加新条目而不删除旧条目

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

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