Naditha

I am new to C#. Can anyone notify me how to add data to an array one by one.
For example if you enter something in a textbox and by a button click it should store in the array.And it will be the array[0] ="" ;
after that again entering something it should store in the other elemnt.
i.e array[1] = "";
and so on.....
I am really glad if some one can help me to sought this out. I know it is simple for experts..
Thanks.


Re: Windows Forms General storing data to an array one by one.

ArranNyc

The following code will add the the text from a textbox to a new array item every time you click on a button. You should add a check to make sure that you have not gone out of bounds.

Code Snippet

public partial class Form1 : Form

{

private int arrayIndex = 0;

private string[] textArray = new string[10];

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

textArray[arrayIndex++] = textBox1.Text;

}

}





Re: Windows Forms General storing data to an array one by one.

Derek Smyth

Hi,

There is nothing wrong with the code above but when it comes to adding data to an array of a fixed size things can get dodgy in C#. In VB you can resize an array but in C#, if I remember correctly, you cannot resize an array. Like I said there is nothing wrong with the code above except what happens if you need to store 11 items, or 12 items, or n number of items. There are a selection of classes in the System.Collections and System.Collections.Generic namespace that provide dynamic arrays which grow and shrink in size as needed.

Code Snippet

//lists automatically grow and shrink as needed

List<string> listOfStrings = new List<string>();

listOfStrings.Add("Hello World");

List<double> listOfDoubles = new List<double>();

listOfDoubles.Add(1.0);

If you then need an array from the list you can call the ToArray() method.

Code Snippet

listOfStrings.ToArray();

The above code becomes

Code Snippet

public partial class Form1 : Form

{

List<string> listOfStrings = new List<string>();

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

listOfStrings.Add(textBox1.Text);

}

}