0

现在,我的代码获取了整个文本文件,并将其全部放入一个文本框中。我试图弄清楚如何做是将文件的每一行放入每个单独的文本框中。

namespace HomeInventory2
{
    public partial class Form1 : Form
    {
        public Form1(string prepopulated)
        {
            InitializeComponent();
            textBoxAmount.Text = prepopulated;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void submitButton_Click(object sender, EventArgs e)
        {
            CreateInventory create = new CreateInventory();
            create.ItemAmount = textBoxAmount.Text;
            create.ItemCategory = textBoxCategories.Text;
            create.ItemProperties = textBoxValue.Text;
            create.ItemValue = textBoxValue.Text;

            InventoryMngr invtryMngr = new InventoryMngr();
            invtryMngr.Create(create);

        }
    }
4

2 回答 2

2

假设行的顺序始终相同并且每个都TextBox属于一行:

IEnumerable<String> lines = File.ReadLines(path);
textBoxAmount.Text = lines.ElementAtOrDefault(0);
textBoxCategories.Text = lines.ElementAtOrDefault(1);
textBoxValue.Text = lines.ElementAtOrDefault(2);
...

Enumerable.ElementAtOrDefault<TSource>方法

返回序列中指定索引处的元素,如果索引超出范围,则返回默认值(在这种情况下为 null)。

于 2012-10-18T22:38:05.480 回答
1

您可以使用 System.IO.File.ReadAllLines(string filename)。它的作用是将文件的每一行读入一个字符串数组。然后,您可以执行以下操作:

using System.IO;


//Namespace, Class Blah Blah BLah


String[] FileLines = File.ReadAllLines("Kablooey");


textBox1.Text = FileLines[0];

textbox2.Text = FileLines[1];

等等。我希望这有帮助 :)

于 2012-10-18T23:03:55.490 回答