Why an array of text boxes cannot be created in C# the same way as in VB.Net?
In VB.Net I can do this, ant it works.

Edited 3 Years Ago by Abel21

Please, post your code for creating the text boxes array in VB and we will try to help you with some thing equivalent in C#

I know it can be creates like:

TextBox[] tbsArray = new TextBox[2];
tbsArray[0] = textBox1;
tbsArray[1] = textBox2;

//or:
TextBox[] tbsArray = new TextBox[] { textBox1, textBox2 };

//or in a loop:
foreach(TextBox tb in new TextBox[] { textBox1, textBox2 })
{
     //...
}

If there is any other way you would like to have it, let us know.
bye

I have written the following code to implement this in VB.NET:Public Class TBdata

    Public txtBox() As TextBox = {Form1.TextBox1, Form1.TextBox2, Form1.TextBox3, Form1.TextBox4}
    Public aTextBoxes(3) As String

    Public Sub DataToArray()
         For i As Integer = 0 To 3
             aTextBoxes(i) = txtBox(i).Text
         Next
    End Sub

End Class

'On the Form, to capture all entries in the text boxes

   Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim d As TBdata = New TBdata()
        d.DataToArray()

    Dim msg As String = ""
        For i As Integer = 0 To 3
            msg = msg & d.aTextBoxes(i) & " : "
        Next

        MessageBox.Show(msg)
    End Sub

Now, why this can't be done in C#?
class TBdata
{
    public string[] aTextBoxes = new string[3];
    public TextBox[] txtBox = new TextBox[] { Form1.textBox1, Form1.textBox2, Form1.textBox3, Form1.textBox4 };

    public void DataToArray()
    {
        for (int i = 0; i < 4; i++)
        {
            aTextBoxes[i] = txtBox(i).Text;

        }
    }
}

In C# all controls in a form are private by default. You can change this by changing the modifier property of each control to public.

Edited 3 Years Ago by tinstaafl

Here is the solution:
Since C# doesn't create an "automatic" instance of the form, a constructor is used to load the textbox controls.

using System.Windows.Forms;


    class TBdata
    {

         public string[] aTextBoxes = new string[5];
        public TextBox[] TextBoxes { get; private set;}

        public TBdata(Form1 form)
        {
            this.TextBoxes = new TextBox[] { form.textBox1, form.textBox2, form.textBox3, form.textBox4 };
        }

        public void DataToArray()
        {
            for (int i = 0; i < TextBoxes.Length; i++)
            {
                aTextBoxes[i] = TextBoxes[i].Text;
            }

        }
   }
This question has already been answered. Start a new discussion instead.