2011-05-14 62 views
1

我有一個以下程序,它從4個文本框中獲取字符串,並將它們放入數組中,並在用戶單擊btnOK後顯示消息(從數組創建)。我有一個叫做btnClear的按鈕,如果點擊它應該清除消息字符串和數組,但它沒有這樣做,我不太確定爲什麼,有人可以看一看並提供建議。無法清除數組和字符串

string[,] namesTable = new string[10, 4]; 
int row = 0; 
string message = ""; 

private void btnOK_Click_1(object sender, EventArgs e) 
{ 

    namesTable[row, 0] = txtFirstName.Text; 
    namesTable[row, 1] = txtSurname.Text; 
    namesTable[row, 2] = txtPosition.Text; 
    namesTable[row, 3] = txtComment.Text; 
    row++; 

    message = "Name.\tSurname\tPosition\tComment\n"; 
    for (int i = 0; i < namesTable.GetLength(0); i++) 
    { 
    if (namesTable[i, 0] != null) 
    { 
     for (int j = 0; j < namesTable.GetLength(1); j++) 
     { 
     message += namesTable[i, j] + "\t"; 
     } 
     message += "\n"; 
    } 
    } 

    MessageBox.Show(message, "Names Table"); 
} 

private void btnClear_Click_1(object sender, EventArgs e) 
{ 
    Array.Clear(namesTable, 0, 4); 
    message = ""; 
} 

如果您需要更多信息,請讓我知道。

回答

1

清除元件的範圍從行包裝在一個多維陣列來排因此 應使用:

Array.Clear(namesTable, 0, 40); 
//     ^^ 
//      | |_The number of elements to clear. 
//      | 
//      |____The starting index of the range of elements to clear. 
+0

@fadjad你能解釋一下,爲什麼當我把它設置爲4並做如下操作:1)輸入4個值,點擊確定,2)再次點擊確定3)點擊清除4)再次點擊確定消息框仍顯示第二行和第三? – 2011-05-14 13:55:31

+0

因爲在你的代碼中:'Array.Clear(namesTable,0,4);'只通過'namesTable [0,4]'0設置'namesTable [0,1]'。 – fardjad 2011-05-14 13:59:39

+0

謝謝,這是有道理的。 – 2011-05-14 14:06:33

0

您正在清除索引0中的數組中的4個值。但是,您的插入代碼會插入row索引處。這可能是你的問題。 row的價值是多少?

要清除everyting陣列中,簡單地做到:

namesTable = new string[10, 4]; 
row = 0; 
+0

row is automaticaly calculated - inc在創建新的「行」數據時進行了重新評估 – 2011-05-14 14:00:11

+0

是否要重新初始化所有行,還是僅重新初始化?在任何情況下,您都需要清除陣列的正確部分。如果你需要清除一切只是'new'一個新的數組,並將'row'設置爲0. – driis 2011-05-14 14:04:34

+0

通過「new new array」你是指清除現有的還是其他的東西? – 2011-05-14 14:12:44

0

如果要清除所有數據,請重新初始化所有數據:

private void btnClear_Click_1(object sender, EventArgs e) 
{ 
    this.namesTable = new string[10, 4]; 
    this.row = 0; 
    this.message = ""; 
}