c# - 将逗号分隔的文本复制到不同的文本框中
问题描述
我正在尝试使用 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?)
解决方案
我可以向您建议的一个简单解决方案是,我假设您的文本顺序也应该与文本框中的特定顺序相匹配。取所有 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();
}
}
}
推荐阅读
- java - 将项目添加到片段中的 ListView
- asp.net - ASP.NET API 控制器 null 类别/表
- c# - OledDBConnection 关闭并将数据读取对象重置为 excel 中的第一个值
- arrays - 如何在python中将负值插入字节数组
- android - 使用 BillOfMaterials 时如何使库的传递依赖项显示在应用程序中?
- python - 如何根据宽度和高度生成 x 和 y 值?
- lua - Lua 在单个表元素中存储多个字符串
- firebase - 如何在 React Native 上处理 Firebase 过期的身份验证令牌
- java - Eclipse 得到“IWAB0014E 发生意外异常”。当我尝试创建一个肥皂客户端时
- android - 在 react-native expo android 中忽略 axios/fetch 调用中的 SSL 证书错误