2016-11-16 14 views
1

编写Windows Forms应用程序时,我发现自己必须根据输入的数量创建可变数量的文本字段。C#中的变量ID

我决定命名这些name1,name2, name3, nameN

现在我想能够将用户的输入保存到文本文件。为此,我需要将文本框中的文本转换为单独的变量,以便将其写入文本文件。

这将导致对这样的循环:

for(i=0; i < totalnames; i++) 
{ 
    string varname= "name" + i; 
} 

不过这样一来,我不能得到文本框中的值。如何从文本框中获取单独的值以将它们写入文本文件?

谢谢

+0

是否要将它们加载回正确的文本框? – garfbradaz

+0

看起来像我的功课... –

+1

this.Controls [varname] .Text,可能。 –

回答

1

当您创建表单控件,保持对它们的引用列表中:

// probably at the class level... 
List<TextBox> myTextBoxes = new List<TextBox>(); 

// then when you create them... 
myTextBoxes.Add(name1); 
// etc. 

后来的后来,当你需要引用它们,使用列表:

foreach (var textBox in myTextBoxes) 
{ 
    // get the value from the text box and use it in your output 
} 
0

您可以创建一个字符串List列表并在其中添加您的名字。然后,使用的StreamWriter在你的文件中添加名称:

 List<string> myListOfNames = new List<string>(); 
     int totalnames = 10; 
     for (int i = 0; i < totalnames; i++) 
     { 
      myListOfNames.Add("name" + i); 
     } 


     using (StreamWriter writer = new StreamWriter("C:\\MyTextFile.txt", true)) 
     { 
      foreach (string name in myListOfNames) 
      { 
       writer.WriteLine(name); 
      } 
     } 
0

这里是我的两个便士的价值,因为OP原本说Windows窗体应用程序 - 我想有一个保存button,其发射时的后面的代码将抓取所有的文本框并保存到文件中。如果需要,您可以自行添加自己的文本框过滤。

首先这里是代码后面的按钮事件:

private void saveToFile_Click(object sender, EventArgs e) 
    { 
     using (StreamWriter writer = new StreamWriter("C:\\k\\saveToFile.txt", true)) 
     { 
      if (this.Controls.Count > 0) 
      { 
       var textBoxes = this.Controls.OfType<TextBox>(); 
       foreach (TextBox textbox in textBoxes) 
       { 
        writer.WriteLine(textbox.Name + "=" + textbox.Text); 
       } 
      } 


     } 
    } 

一个简单的福尔为了证明这一点,每个TextBox具有NAME1

enter image description here

的名称这里还有一个输出文件的例子:

enter image description here

改进

  1. 过滤的文本框 - 你可能只需要对一些文本框特定名称做到这一点。
  2. 加载文件。我已经将文本框的名称添加到文件中,所以在理论上您可以将数据加载回文本框。