从文本框中向 C# 数组添加元素

adding an element to a C# array from a text box

我正在努力使用 C# Windows Forms 从文本框中将元素添加到数组中。她是我目前所拥有的:

int[] id;

private void btnButton1_Click(object sender, EventArgs e)
    {
        //INSERTION SORT
        int newItem = txtAddElement.text;

        //CODE HERE TO ADD ELEMENT TO ARRAY


        //CODE BELOW THEN SORTS ARRAY INTO CORRECT ORDER

        int element;
        int temp;

        for (int i = 1; i < id.Length; i++)
        {
            element = i - 1;

            while (element >= 0 && id[element] > id[element + 1])
            {
                temp = id[element];
                id[element] = id[element + 1];
                id[element + 1] = temp;
            }
        }

        for (int i = 1; i < id.Length; i++)
        {
            lstPlayers.Items.Add(id[i]);
        }

        txtAddElement.Text = "";
    }

我知道这种插入排序是有效的,因为我以前手动添加了一些值,但是现在基本部分似乎让我感到困惑。

我想要的是让程序 运行 使用一个空数组,如上所述,当我在 txtAddElement 中输入一个值时,我想使用一个按钮 btnAddToArray 来将这个值插入到数组中。例如:

如果我在 txtAddElement 中键入 12,然后按 btnAddToArray,我希望数组现在有 1 个 12 项,如果是然后通过 [= 添加另一个数字13=],比方说 7,然后按下 btnAddToArray 按钮,我希望数组有 2 个值 [12, 7] 一旦我掌握了这个然后我需要做的就是将插入排序添加到这个.

错误:

代码片段

   int[] id;

    private void btnLogOn_Click(object sender, EventArgs e)
    {
        Array.Resize(ref id, id.Length + 1); //Object reference not set to an instance of an object.
        id[id.Length - 1] = Convert.ToInt16(txtLogOn.Text);

        //INSERTION SORT
        int element;
        int temp;

已解决:

  int[] id = new int[0];

您无法添加到数组。您应该使用 List<T> 例如

  List<int> id;
  ...

  id.Add(123);

重新调整数组的大小(不推荐)

  int[] id;
  ... 
  Array.Resize(ref id, id.Length + 1);
  id[id.Length - 1] = 123;