将用逗号分隔的文本复制到不同的文本框中

问题描述

我正在尝试使用Windows窗体开发应用程序,以读取* .txt文件的内容,其中包含以下信息:

12.14,12.00,11.98,12.01,12.09,12.05,11.50,11.48,11.56,11.52,11.53,12.08,11.13,11.12,12.10,12.14,11,09,12.12,11.16,12.17,11.11,11.19,12.15,11.10,12.11,

,并且需要将每个单独的值复制到TextBox(总共有60个TextBox)。

我尝试使用下面的代码,但是我不知道如何单独处理所有TextBox

using System;
using System.IO;

public class Sample
{
    public static void Main() {
        using (StreamReader reader = new StreamReader("yourfile.txt")) {
            string line = null;
            while (null != (line = reader.ReadLine())) {
                string[] values = line.Split(',');
                float[] numbers = new float[values.Length - 1];
                for (int i = 1; i < values.Length - 1; i++)
                    numbers[i - 1] = float.Parse(values[i]);

                
            }
        }
    }
}

(此代码是从URL How to read values from a comma separated file?复制的)

解决方法

我可以建议您的一个简单解决方案是,我假设您的文本顺序也应与文本框中的特定顺序匹配。占用所有60个文本框,并将其Tag属性设置为基于零的索引的整数值。一个是0,最后一个是59

然后在您的代码中,假设它当前在Form本身中运行,您只需将代码更改为此:

private void LoadFile() 
{
    // get all textbox in the form with some sort of tag
    var textboxes = this.Controls.OfType<TextBox>().ToList().Where(txt => txt.Tag != null).ToList();

    // will contain all numbers from the file ordered
    var orderedNumbers = new List<float>();

    using (StreamReader reader = new StreamReader("yourfile.txt")) {
        string line = null;
        while (null != (line = reader.ReadLine())) {
            string[] values = line.Split(',');
            float[] numbers = new float[values.Length - 1];
            for (int i = 1; i < values.Length - 1; i++)

                numbers[i - 1] = float.Parse(values[i]);
            // add the numbers of the line to the collection
            orderedNumbers.AddRange(numbers);
            
        }
    }

    // loop to update the textboxes
    for(int i = 0; i < orderedNumbers.Count; i++)
    {
        // find the textbox with current index
        var textBox = textboxes.FirstOrDefault(txt => txt.Tag.ToString() == i.ToString());

        // if we found the text box we can update
        if(textBox != null)
        {
            textBox.Text = orderedNumbers[i].ToString();
        }
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...