I'm tasked with having a button that will set a value entered to an array. The user will enter a value press the button, once the button is pressed the value the user entered is stored into an array. My teacher (yes this is a homework question) said that he wants it to do only one value at a time.
The problem i'm running into is, I just don't know what to write in order for this to happen. I've tried looking at what all I can do in the event but that has gotten me nowhere, unless the answer was there and I just completely missed it.
Any suggestions on where to look, or an idea of what to write would be awesome.
private void addToArray_Click(object sender, EventArgs e)
{
Button bclick = (Button) sender;
string variables = addArrayTextBox.Text;
int []vars = new int[5];
vars = parseVariableString(variables);
int numberIndex = 0;
for (int i = 0; i < vars.Length; i++)
{
int indexNumber = vars.Length;
numberIndex = indexNumber;
}
integerTextBox.Text = numberIndex.ToString();
}
Is what I currently have typed up.
to get you started
let's get the graphical designer stuff out of the way first:
button_click
event handler next, you'll probably want your array to stay in scope, the simplest way to do that is to declare it as a field of your Form1
instance, and then instantiate and/or initialize it in the `Form1 Constructor.
Then you can access it from your event handler
example:
public partial class Form1 : Form
{
int[] vars;
int intergersEntered;
public Form1()
{
InitializeComponent();
vars = new int[5];
intergersEntered = 0;
// insert other initialization here
}
private void button1_Click(object sender, EventArgs e)
{
vars[0] = int.Parse(textBox1.Text);
intergersEntered++;
textBox2.Text = intergersEntered.ToString();
}
...
I'm not sure I get your question based on your code. Paraphrasing, you want to increase an array length by 1 when a button is pressed, yes?
public partial class Form1 : Form
{
private int[] vars;
public Form1()
{
InitializeComponent();
vars = new int[5];
}
private void button1_Click(object sender, EventArgs e)
{
int[] tmp = new int[vars.Length + 1];
vars.CopyTo(tmp, 0);
vars = tmp;
}
}
It seems to me that you need to just resize the array to one higher each time the "Add To Array" button is clicked:
private void addToArray_Click(object sender, EventArgs e)
{
//Calculate the new size of the array
int newLength = arrayOfIntegers.Length + 1;
//Resize the array
Array.Resize(ref arrayOfIntegers, newLength);
//Add the new value to the array
//Note that this will fail if the textbox does not contain a valid integer.
//You can use the Integer.TryParse method to handle this
arrayOfIntegers[newLength] = Integer.Parse(addArrayTextBox.Text);
//Update the text box with the new count
integerTextBox.Text = newLength.ToString();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.