C#加载.txt文件并在listview中显示

时间:2015-11-08 00:49:54

标签: c# winforms listview import

所以我尝试做的是加载.txt文件,加载.txt文件后,它将在listView中显示.txt文件中的内容。

这是我的加载代码。

        List<String> proxies = new List<string>();
    private void loadProxiesToolStripMenuItem_Click(object sender, EventArgs e)
    {
        loadProxies();
    }

    private void loadProxies()
    {
        this.Invoke(new MethodInvoker(delegate
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "TXT files|*.txt";
            ofd.Title = "Load Proxies";
            var dialogResult = ofd.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                proxies = new List<string>();
                Parallel.ForEach(System.IO.File.ReadLines(ofd.FileName), (line, _, lineNumber) =>
                {
                    if (line.Contains(":"))
                    {
                        //loadedCombo.Add(line);
                        proxies.Add(line);
                    }
                    else
                    {
                        //MessageBox.Show("Hmm, thats not a combolist - please try again");
                    }
                });
            }

            txt_proxies.Text = "Proxies Loaded: " + proxies.Count.ToString();

        }));
    }

我希望它在listView中显示名为&#34; proxyView&#34;。

所以我试图说出来,我可以加载.txt并更改计数,但是它没有将.txt文件中的内容添加到列表视图中。

非常感谢。

1 个答案:

答案 0 :(得分:3)

要将商品添加到ListView,您可以使用yourListView.Items.Add(text)

例如:

private void loadProxies()
{ 
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "TXT files|*.txt";
    ofd.Title = "Load Proxies";
    var dialogResult = ofd.ShowDialog();
    if (dialogResult == DialogResult.OK)
    {
        foreach (var line in System.IO.File.ReadLines(ofd.FileName))
        {
            if (line.Contains(":"))
                proxyView.Items.Add(line);
        }
    }
}