0

does anyone knows how to append a string to a variable name?

public void editForm(DataGridView dg)
{
   for(int i=0; i<=dg.Columns.Count-1;i++)
   {
      TextBox txt=new TextBox();   //I want to append i to txt. like -->TextBox txt&i
   }
}

Then I'll add the textboxes created to a Form.

user2837650
  • 23
  • 1
  • 1
  • 5

1 Answers1

1

That's not possible in C#.

You can achieve something similar using some sort of collection, like an array,

public void editForm(DataGridView dg)
{
    TextBox[] textBoxes = new TextBox[dg.Columns.Count];
    for(int i = 0; i <= dg.Columns.Count-1; i++)
    {
        textBoxes[i] = new TextBox();  
    }
}

Although, you could something nicer using Enumerable.Range,

public void editForm(DataGridView dg)
{
    var textBoxes = 
        Enumerable.Range(0, dg.Columns.Count)
                  .Select(i => new TextBox())
                  .ToArray();
}

Either way, you can then add your text boxes to the form.

rae1
  • 6,066
  • 4
  • 27
  • 48