简体   繁体   English

如何从csv文件读取到ListBox-WPF?

[英]How to Read from a csv File into a ListBox - WPF?

I'm trying to read from a document that has a list of students with their first name, last name, student id, email. 我正在尝试从一个包含有学生的名单的文档中读取他们的名字,姓氏,学生证,电子邮件。

I've successfully created/designed the xmal file with a listBox (see attachment). 我已经成功创建/设计了带有listBox的xmal文件(请参阅附件)。 在此处输入图片说明

But I'm having difficulties writing the code in the try section, which will read from the document into the listBox in such order that each of the specific read data must go under those relevant textblocks. 但是我很难在try部分中编写代码,该部分将从文档中读取代码到listBox中,以使每个特定的读取数据都必须位于这些相关的文本块下。 for instance first name should go under first name, and so on. 例如,名字应该放在名字之下,依此类推。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;

namespace MemberList
{

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }


        string filePath = @"C:\Users\User\DEMO\MemberList.csv";

        private void Member_List_Load(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.Default);

            List<string> lines = File.ReadAllLines(filePath).ToList();

            while (!sr.EndOfStream)
            {

                try
                {



                    foreach (var line in lines)
                    {
                        string[] entries = line.Split(';');
                        textblock1 = entries[0];
                        textblock2 = entries[1];
                        textblock2 = entries[2];
                        textblock2 = entries[3];

                    }

                }
                catch (Exception)
                {

                    throw;
                }
                finally
                {

                }
            }
        }
    }
}

You're not using the recommended MVVM pattern; 您没有使用推荐的MVVM模式; I'm not going to sermon you about that, just look into it to build better applications in the future. 我不会讲这个,只是在将来研究它以构建更好的应用程序。

So, about your actual problem, you should use x:Name instead of Name for your text boxes; 因此,关于您的实际问题,您应该在文本框中使用x:Name而不是Name look at this question and its answers . 这个问题及其答案 This way, they will be referencable in your code behind, and your code should work. 这样,它们将在后面的代码中被引用,并且您的代码应该可以工作。

Edit 1: You should also use the Text property of your text boxes in you code behind: 编辑1:您还应该在后面的代码中使用文本框的Text属性:

textbox1.Text = entries[0];

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

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