2013-03-05 170 views
0

我的任務是設置一個按鈕,它將設置一個輸入到數組中的值。用戶將按下按鈕輸入一個值,一旦按下按鈕,用戶輸入的值就被存儲到一個數組中。我的老師(是的,這是一個家庭作業問題)說,他希望它一次只能做一個價值。每按一次按鈕都會增加一個數組點擊

我遇到的問題是,我只是不知道該寫些什麼才能發生。我試着看看我能做些什麼,但那已經讓我無處可去,除非答案在那裏,而我完全錯過了它。

任何關於在哪裏尋找的建議或想寫什麼的想法都會很棒。

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

,讓你開始

讓我們的圖形設計的東西出來的第一方式:

  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

0

我不確定根據您的代碼得到您的問題。釋義,你想在按下按鈕時將數組長度增加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; 
    } 
} 
0

在我看來,你需要在陣列每次只需調整到一個更高的「添加到陣列「按鈕被點擊:

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(); 
} 
相關問題