C#将列表值读入文本框

时间:2018-02-11 20:13:20

标签: c# list csv

我现在已经坚持这个问题一段时间了。我能够从一堆(100)文本框中读取信息并将数据保存到CSV文件中,但是将这些信息读回到表单中让我有点糊涂,我只是尝试加载第一个11字符串开头。我可以将CSV加载到列表中,但我似乎无法将该数据从列表移动到我的文本框中。我的做法是否缺少一些东西?

        public List<string> LoadCsvFile(string filePath)
    {
        var reader = new StreamReader(File.OpenRead(filePath));
        List<string> searchList = new List<string>();


        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            searchList.Add(line);
            for (int i = 0; i < 11; i++)
            {
                string date = searchList[i];
                string dropdownindex = searchList[i];
                LasttextBox.Text = searchList[i];
                FirsttextBox.Text = searchList[i];
                EmailtextBox.Text = searchList[i];
                PhonetextBox.Text = searchList[i];
                HometextBox.Text = searchList[i];
                InfotextBox.Text = searchList[i];
                PrimarytextBox.Text = searchList[i];
                EmailtextBox.Text = searchList[i];
                SecondaryEmailtextBox.Text = searchList[i];
            }
        }
        return searchList;
    }

我得到的错误是:

  

System.ArgumentOutOfRangeException:&#39;索引超出范围。一定是   非负面且小于集合的大小。参数名称:   索引&#39;

感谢您提供的任何帮助。

2 个答案:

答案 0 :(得分:1)

您在使用字段时会混淆线条,并且根据您尝试执行的操作,您甚至不需要列表。您似乎正在尝试将字段值分配给文本框。

假设您的csv文件与下面的内容类似(顺便说一下,您的电子邮件文本框是重复的):

日期,DropDownIndex,姓,名,电子邮件,电话,主页,信息,主,电子邮件,SecondaryEmail

您可以使用Linq将您的CSV文件解析为包含所需值的匿名类,然后循环并将其分配给文本框

例如:

var csvRecords = File
            .ReadAllLines(filePath)
            .Select(c => c.Split(',')).Select(c => new
            {
                Date = c[0],
                DropDown = c[1],
                LastName = c[2],
                FirstName = c[3],
                Email = c[4],
                Phone = c[5],
                Home = c[6],
                Info = c[7],
                Primary = c[8],
                Email2 = c[9],
                SecondaryEmail = c[10]
            }).ToList();

foreach (var csvRecord in csvRecords)
        {
            var date = csvRecord.Date;
            var dropdownindex = csvRecord.DropDown;
            LasttextBox.Text = csvRecord.LastName;
            FirsttextBox.Text = csvRecord.FirstName;
            EmailtextBox.Text = csvRecord.Email;
            PhonetextBox.Text = csvRecord.Phone;
            HometextBox.Text = csvRecord.Home;
            InfotextBox.Text = csvRecord.Info;
            PrimarytextBox.Text = csvRecord.Primary;
            EmailtextBox.Text = csvRecord.Email2;
            SecondaryEmailtextBox.Text = csvRecord.SecondaryEmail;
        }

您需要考虑的一些事情是,如果您的CSV文件只包含逗号分隔符而没有双引号限定符,因为实际值中可能会有逗号,这会使您的各个字段的位置失效。如果您仍想通过该方法返回List,则无法返回匿名类型列表,因此您需要创建一个类,然后在Linq select中使用new,而不是使用new并以相同的方式分配字段。

答案 1 :(得分:1)

这种方法更具可扩展性,即只要您可以控制文本框的名称,它就可以使用任意数量的csv文件行和/或文本框。此设计忽略了csv文件中没有

文本框的行
public Form1()
{
    InitializeComponent();

    //simulate a list loaded from a csv file
    IList<string> stringsFromCsv = new List<string>
    {
        "from csv line dog",
        "from csv line cat",
        "from csv line fish",
        "from csv line frog",
        "from csv line squirrel",
        "from csv line turtle",
        "from csv line squid",
        "from csv line bass",
        "from csv line tiger",
        "from csv line lion"
    };

    //make a collection of all the controls in the groupbox (or form, or whatever)
    Control.ControlCollection controls = groupBox1.Controls;

    int listIndex = 0;

    //loop based on the number of items from the csv file
    while (listIndex <= stringsFromCsv.Count - 1)
    {
        //create a text box name from the current list index
        string expectedTextBoxName = "textBox" + ((listIndex + 1).ToString());

        //this is brute force, but step thru all the controls until
        //you find a text box whose name matches 
        foreach (Control control in controls)
        {
            //skip the control if its not a text box
            if (control.GetType().Name != "TextBox")
                continue;

            if (control.Name == expectedTextBoxName)
            {
                control.Text = stringsFromCsv[listIndex];
                break;
            }

        }

        listIndex = listIndex + 1;

        if (listIndex > stringsFromCsv.Count - 1)
            break;
    }
}

enter image description here