I am struggling to add an element into an array from a text box using C# Windows Forms. hers what I have so far:
int[] id;
private void btnButton1_Click(object sender, EventArgs e)
{
//INSERTION SORT
int newItem = txtAddElement.text;
//CODE HERE TO ADD ELEMENT TO ARRAY
//CODE BELOW THEN SORTS ARRAY INTO CORRECT ORDER
int element;
int temp;
for (int i = 1; i < id.Length; i++)
{
element = i - 1;
while (element >= 0 && id[element] > id[element + 1])
{
temp = id[element];
id[element] = id[element + 1];
id[element + 1] = temp;
}
}
for (int i = 1; i < id.Length; i++)
{
lstPlayers.Items.Add(id[i]);
}
txtAddElement.Text = "";
}
I know this insertion sort works because I have manually added some values in previously, however the basic part now seems to be tripping me up.
What I want is for the program to run with an empty array, as coded above, when I enter a value into txtAddElement I want to use a button btnAddToArray to insert this value into the array. For example:
if i type 12 into txtAddElement, and then press btnAddToArray, i would like the array to now have 1 item of 12, If was was to then add another number via the txtAddElement, lets say 7, and press the btnAddToArray button, I want the array to then have 2 values [12, 7] once I have mastered this then alls i need to do is add the insertion sort to this.
error:
CODE SNIPPET
int[] id;
private void btnLogOn_Click(object sender, EventArgs e)
{
Array.Resize(ref id, id.Length + 1); //Object reference not set to an instance of an object.
id[id.Length - 1] = Convert.ToInt16(txtLogOn.Text);
//INSERTION SORT
int element;
int temp;
SOLVED:
int[] id = new int[0];