从文本文件插入到textBox中

时间:2014-02-19 16:27:42

标签: c#

所以我想做的是将一个txt文档加载到C#中,并在txt文档的每一行中将该部分写入文本文件的不同文本框中。

NTM-120 = textBox1
NTM-130 = textBox2
NTM-140   etc....
NTM-150
NTM-160
NTM-170

这可能吗?

像这样的事情?????

using (StreamReader reader = File.OpenText("yourFileName.txt"))
{
    textBox1.Text = reader.ReadLine();
    textBox2.Text = reader.ReadLine();
    textBox3.Text = reader.ReadLine();
    textBox4.Text = reader.ReadLine();
    textBox5.Text = reader.ReadLine();
    textBox6.Text = reader.ReadLine();
    textBox7.Text = reader.ReadLine();
    textBox8.Text = reader.ReadLine();
    textBox9.Text = reader.ReadLine();
}

4 个答案:

答案 0 :(得分:1)

试试这个:

int count=1;
var lines = File.ReadAllLines("C:\\Data.txt");
int totalTxtBoxControls=20;
if(lines.Count==totalTxtBoxControls)
{
((TextBox)this.Controls.Find("TextBox" + count, true)[0]).Text = line[count-1];
count++;
}

答案 1 :(得分:0)

听起来你还没有真正想过怎么做也没想过,但基本上是

string[] lines = System.IO.File.ReadAllLines("source.txt");
foreach(string line in lines)
{
    // put you logic on which line goes to which textbox
}

嗯?

答案 2 :(得分:0)

你可以使用

private void button1_Click(object sender, EventArgs e)
{
    using (StreamReader sr = new StreamReader(filePath))
    {
        int lineNumber = 0;
        while (!sr.EndOfStream)
        {
           lineNumber++;
           var readLine = sr.ReadLine();
           if (readLine != null)
           {
               TextBox textBox = GetControle(this, "textBox"+lineNumber);
                if (textBox != null)
                {
                    textBox.Text = readLine;
                }
            }
        }
     }
}

private TextBox GetControle(Control ctrlContainer, string name)
{
    foreach (Control ctrl in ctrlContainer.Controls)
    {
        if (ctrl.GetType() == typeof(TextBox))
        {
            if (ctrl.Name == name)
            {
                return (TextBox)ctrl;
            }
        }
         if (ctrl.HasChildren)
            GetControle(ctrl, name);
    }
    return null;
}

答案 3 :(得分:0)

试试这个。它为文本文件中的每一行动态创建一个文本框!

TableLayoutPanel tlp = new TableLayoutPanel();
tlp.Dock = DockStyle.Fill;

int row = 0;
foreach (string s in File.ReadAllLines("file.txt"))
{
    tlp.RowStyles.Add(new RowStyle());

    TextBox tb = new TextBox();
    tb.Text = s;
    tlp.Controls.Add(tb, 0, row++);
}

this.Controls.Add(tlp);