Shruti Rao

Shruti Rao

  • NA
  • 9
  • 0

How do I access dynamically created textboxes and save their values(text) into a file?

Mar 22 2010 5:57 AM

Hello,
Could you  please suggest me how I can save the contents of these dynamically created textboxes into a file? I am not able to access these dynamically created textboxes.

This is the code I've written to create text boxes.

private void button2_Click(object sender, EventArgs e)
{
   int left1 = 80;
   string num = textBox2.Text;
   int n = Int32.Parse(num);
   int b = 1;
   for (int k = 1; k <=n; k++)
   {
      int top1 = 30, a = 0;
      for (int p = 1; p <= 4; p++)
      {
         string str = "txt" + b + a;
         TextBox txt = new TextBox();
         panel1.Controls.Add(txt);      //these textboxes are added on the panel
         txt.Name = str;
      txt.Size = new Size(30, 20);
      txt.Top += top1;
      top1 += 30;
      txt.Left = left1;
      txt.BackColor = Color.Cornsilk;
      a++;
      txt.Show(); 
      }
   left1 += 100;
   } b++;
}

Now with a click of another button, I want to access the text I've entered in these textboxes (that are present on the panel) and save them in a file.

This is the code I've written,

private void button3_Click(object sender, EventArgs e)
{
string num = textBox2.Text;
int n = Int32.Parse(num);

string dir = textBox1.Text;
string file = "@H:\\" + dir + "\\Test.txt";
int a = 1, b = 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j < 4; j++)
{
StreamWriter writer = new StreamWriter(file);
string str = "txt" + b + a;
a++; 

//How can I access the [Name] of those  textbox  I've created dynamically on the panel????
//I want to retrieve the text of these textboxes and save it in a file

string data = str.Text;  //Error 

string delm1 = "-";
writer.Write(data);
writer.Write(delm1);
writer.Close();
}
b++;
string delim2 = "$";
StreamWriter writer1 = new StreamWriter(file);
writer1.Write(delim2);
writer1.Close();
}

Could you please suggest an effective code?
Thank you in advance.

Answers (5)