How to insert input into an array from a text box in C#

2.7k Views Asked by At

I would like to insert the user input into an array when the user clicks the submit button. This is what I wrote but it doesnt seem to work. The form is called form1 and it is its own class, the textbox is textbox1. Note: I am a newbie in programming.

//This is my array
private string[] texts = new string[10];

        public string[] Texts
        {
            get { return texts; }
            set { texts = value; }
        }

//I then attempt to insert the value of the field into the textbox
form1 enterDetails = new form1();
for(int counter = 0; counter<Texts.Length; counter++)
{
texts[counter]=enterDetails.textbox1.Text;
}
1

There are 1 best solutions below

0
On

You have done some silly mistakes here:

  1. In setter of Texts property you should say

    texts = value;
    

    instead of guestNames = value;

  2. You don't need to create a new instance of your form1 as all the code you written above is already inside the form1 class. If not then try to get the same instance of form1.

  3. Not necessary but you should set your property not the field.

    Replace

    texts[counter] = .......
    

    with

    Texts[counter] = ..........
    

So, your complete code should look like:

    public form1() //Initialize your properties in constructor.
    {
        Texts = new string[10]
    }

    private string[] texts;

    public string[] Texts
    {
        get {return texts; }
        set { texts = value; }
    }

    for(int counter = 0; counter<Texts.Length; counter++)
    {
        Texts[counter]=this.textbox1.Text;
    }