2015-03-08 49 views
-1

我在我的应用程序中有30多个文本框,我想按顺序在每个文本框中添加文本文件的每一行。从文本文件中的单独文本框中添加每行C#

private void button2_Click(object sender, EventArgs e) 
{ 
    if (path1 != null && Directory.Exists(path1)) 
    { 
     var lines = File.ReadAllLines(path1); 
     foreach (var line in lines) 
     { 
      //what is here ? 
     } 
    } 
} 

所以,如果我在我的文本文件:
- 狗
- 计算机
- 钱

我想有:

  • TextBox1的第一排(狗)
  • TextBox2中第二排(计算机)
  • textbox3第三排(钱)

更新:加入TextBoxes列表。现在,我怎样才能一次访问一个文本框,并在foreach中使用它?

private void button2_Click(object sender, EventArgs e) 
{ 
    List<TextBox> textBoxes = new List<TextBox>(); 

    for (int i = 1; i <= 37; i++) 
    { 
     textBoxes.Add((TextBox)Controls.Find("textBox" + i, true)[0]); 
    } 

    if (path1 != null && Directory.Exists(path1)) 
    { 
     var lines = File.ReadAllLines(path1); 
     foreach (var line in lines) 
     { 
      //what is here ? 
     } 
    } 
} 
+0

你可以将所有文本框添加到列表中。在foreach中你可以访问它。 – cSteusloff 2015-03-08 21:18:44

+0

@cSteusloff我添加了一个列表。你能回答我最近更新的问题吗?一个片段会很好。 – 2015-03-08 21:35:11

+0

你到底想要解决什么问题?到目前为止,它看起来像一个不好的决定,说实话... – walther 2015-03-08 21:50:49

回答

0

转换在foreach到并使用索引来访问当前行以及指定的文本框:

if (path1 != null && File.Exists(path1)) 
{ 
    var lines = File.ReadAllLines(path1); 
    for (var lineIndex = 0; lineIndex < Math.Min(lines.Length, textBoxes.Count); lineIndex++) 
    { 
     textBoxes[lineIndex].Text = lines[lineIndex]; 
    } 
} 
+0

谢谢@Thomas。它不会打印任何东西。 – 2015-03-08 21:59:18

+0

我认为“Directory.Exists(path1)”是你的问题。如果path1是文件名,并且因此该块未执行,它将返回false。我在我的答案中将其更正为File.Exists。 – 2015-03-08 22:11:44

0

如果你想用你的foreach循环,试试这个:

var textBoxIndex = 0; 
foreach (var line in lines) 
{ 
    textBoxes[textBoxIndex++].Text = line; 
} 
0

这里是我的建议

public partial class Form1 : Form 
{ 
    string Path1 = "MyFile.txt"; 

    List<TextBox> textBoxes = new List<TextBox>(); 

    public Form1() 
    { 
     InitializeComponent();    
    }   

    private void button2_Click(object sender, EventArgs e) 
    { 
     foreach (Control item in this.Controls) 
     { 
      if (item is TextBox) 
      { 
       textBoxes.Add((TextBox)item); 
      } 
     } 

     string[] lines = File.ReadAllLines(Path1); 

     for (int i = 0; i < lines.Length; ++i) 
     { 
      textBoxes[i].Text = lines[i]; 
     }   
    } 
} 
+0

或者你可以把所有的文本框放在flowLayoutPanel上,并在foreach循环中写入“this.flowLayoutPanel1.Controls中的控制项”@alexander – Mojtaba 2015-03-08 22:30:53

+0

我假定文本文件存在并且不为null @Alexander – Mojtaba 2015-03-08 22:44:06

相关问题