首页 > 解决方案 > 将逗号分隔的文本复制到不同的文本框中

问题描述

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

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

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

我尝试使用下面的代码,但我不知道如何TextBox单独使用 all 。

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 separator file?

标签: c#winformsstreamreadercomma

解决方案


我可以向您建议的一个简单解决方案是,我假设您的文本顺序也应该与文本框中的特定顺序相匹配。取所有 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();
        }
    }
}

推荐阅读