每按一次按钮都会增加一个数组点击

问题描述:

我的任务是设置一个按钮,它将设置一个输入到数组中的值。用户将按下按钮输入一个值,一旦按下按钮,用户输入的值就被存储到一个数组中。我的老师(是的,这是一个家庭作业问题)说,他希望它一次只能做一个价值。每按一次按钮都会增加一个数组点击

我遇到的问题是,我只是不知道该写些什么才能发生。我试着看看我能做些什么,但那已经让我无处可去,除非答案在那里,而我完全错过了它。

任何关于在哪里寻找的建议或想写什么的想法都会很棒。

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(); 
} 

是我现在输入的内容。

+0

winforms我推测? – 2013-03-05 19:05:57

+0

您的要求不清楚。你能否看看你的问题,然后更清楚地描述你要做的事情? – 2013-03-05 19:08:13

+0

'parseVariableString()'做了什么? – 2013-03-05 19:09:21

,让你开始

让我们的图形设计的东西出来的第一方式:

  1. 让你的WinForms项目
  2. 拖放按钮
  3. 拖放删除文本框
  4. 双击该按钮创建一个button_click事件处理程序

下一个,你可能会想你的阵列留在范围,做到这一点最简单的方法是将其声明为您Form1实例的字段,然后实例和/或在`Form1的初始化构造函数。

然后你可以从你的事件处理程序访问它

例如:

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(); 
    } 
... 
+0

非常感谢。我当时正在考虑手头的问题。 – jimjam456 2013-03-05 19:37:55

+0

这种方法不会每次都重写数组的第一个索引吗?我对该任务的阅读是“将值添加到数组中”。所以每次数组的大小都会增加一个,并将新输入的值添加到新的索引中。 – 2013-03-05 19:48:43

+0

@ChrisDunaway它不是一个完整的项目。它只是为了给OP提供他需要的基本框架。我不妨写''在这里对数组做些什么' – 2013-03-05 19:52:01

我不确定根据您的代码得到您的问题。释义,你想在按下按钮时将数组长度增加1,是的?

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; 
    } 
} 

在我看来,你需要在阵列每次只需调整到一个更高的“添加到阵列“按钮被点击:

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(); 
}