开发者

Unable to clear array and string

开发者 https://www.devze.com 2023-03-05 17:10 出处:网络
I have a following program, it takes strings from 4 textboxes and puts them into array and displays the message(created from the array) after user clicks on btnOK. I have a button called btnClear whic

I have a following program, it takes strings from 4 textboxes and puts them into array and displays the message(created from the array) after user clicks on btnOK. I have a button called btnClear which if clicked should clear both the message string and array but it's not doing it and I'm not quite sure why, can someone have a look and advise.

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

If you need mo开发者_如何学编程re info please let me know.


The range of cleared elements wrap from row to row in a multi-dimensional array therefore You should use:

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


If you want to clear all your data, so reinitialize all:

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


You are clearing 4 values in the array from index 0. However, your insert code inserts at the row index. This is likely to be your problem. What is the value of row ?

To clear everyting in the array, simply do:

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

精彩评论

暂无评论...
验证码 换一张
取 消