0

Possible Duplicate:
How do I make a Control Array in C# 2010.NET?

i have 10 textbox in my window form can i write a source code in C# as in VB6 to access all the textbox with index value where all the textbox having the same name?

Community
  • 1
  • 1

4 Answers4

4

VB6 style Control arrays are not supported, but you can easily accomplish this by addiing each one the controls to a seperately-declared array or list.

private List<Textbox> txtSameName = new List<Textbox>();

in constructor, after InitializeComponent:

txtSameName.Add(txtOne);
txtSameName.Add(txtTwo);
txtSameName.Add(txtThree);
txtSameName.Add(txtFour);

then you can iterate by index or via foreach:

for (int 1 = 0; i < txtSameName.Length; i++)
{
   txtSameName[i].Text = string.empty;
}

to wire up a common handler:

foreach (Textbox tb in txtSameName)
{
   tb.TextChanged += new EventHandler(txtSameName_TextChanged);
}

and then a single handler as follows:

private void txtSameName_TextChanged(object sender, EventArgs e)
{
   Textbox tb = sender as Textbox;
   tb.BackColor = Colors.Yellow;
}
tcarvin
  • 10,715
  • 3
  • 31
  • 52
0

Name is irrelevant really in Winforms. You can just add the textboxes to an array and index them that way.

Ian
  • 4,885
  • 4
  • 43
  • 65
0

IF you only need to access the controls I think you could do something like this:

public TextBox[] TextBoxesArray
{
    get
    {
        return Controls.OfType<TextBox>().Select(control => control).ToArray();
    }
}

I'm not sure how to extend this to allow adding/removing TextBoxes from the array and update the Controls collection at the same time.

0

There is no "built-in" way like in VB6. However, assuming your text boxes are named txtBox0, txtBox1, etc., and there are fewer than 10...

If you use the method shown in this answer, then you could write something like:

var myTextBoxes =
    this.FilterControls(c => c is TextBox)
        .Where(c => c.Name != null && c.Name.StartsWith("txtBox"))
        .OrderBy(c => c.Name)
        .ToArray();

Now myTextBoxes should contain your array.

Community
  • 1
  • 1
Scott Whitlock
  • 13,739
  • 7
  • 65
  • 114