Windows 表单中的 C#:"Index was outside the bounds of the array" 尝试自动添加新的 space

C# in Windows Forms : "Index was outside the bounds of the array" at a try to auto-add new space

我真的不明白这个错误是从哪里来的以及如何修复它。
我的想法是每次读取新对象时将 space 增加 1,这就是我使用 int m = a.GetLength(0)+1;
的原因 a[m, j] = Convert.ToString(m); 是 j=1 这意味着帐户的数量实际上是 m,数组的最后一个位置。
每次我想添加新元素时,我怎样才能在不写很多行并用 +1 行在另一个行中复制矢量的情况下完成这项工作?

// "Index was outside the bounds of the array."
// "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in code.exe"

带代码的照片&错误:

    private void adauga_Click(object sender, EventArgs e)
    {

        int m = a.GetLength(0)+1;
            for (int j = 0; j < 7; j++)
            {   a[m, j] = Convert.ToString(m);
                a[m, j] = textnume.Text;
                a[m, j] = textprenume.Text;
                a[m, j] = textcnp.Text;
                a[m, j] = textserie.Text;
                a[m, j] = textnumar.Text;
                a[m, j] = textdebcre.Text;
                b[m] = Convert.ToInt32(textsuma.Text); } }

其中 a 和 b 是: 静态字符串 []a = 新字符串 [1,1]; static int[] b=new int1;

当您试图访问数组中不存在的条目时出现问题。这是不允许的,因此抛出异常。

此时您的数组具有您在第一行定义的大小:

static string [,] a= new string [1,1];

这意味着唯一有效的条目位于 a[0,0]。要访问其他条目,您需要明确地将数组大小调整为您想要的新大小:How to resize multidimensional (2D) array in C#?

我猜您想在用户单击该按钮后将应用程序中的条目保存到该数组中。我建议您使用对象和 List<T> 而不是多维数组来解决此问题:

创建一个包含您要保存的属性的对象,类似于:

class MyClass
{
    public string Nume {get; set;}
    public string PreNume {get; set;}
    //your other properties here
}

然后创建一个列表来保存您的对象。列表具有数组的优势,即使在您定义它们之后它们也可以增长。 List中的T是任意的class,这里可以使用我们上面定义的MyClass。所以:

List<MyClass> myList = new List<MyClass>();

现在把它们放在一起:

private List<MyClass> _myList = new List<MyClass>();
private void adauga_Click(object sender, EventArgs e)
{
    //create a myClass Object
    var myClass = new MyClass();
    myClass.Nume = textnume.Text;
    myClass.PreNume = textprenume.Text;
    //continue here...

    //add it to the list
    _myList.add(myClass);
}

首先,最后只有textdebcre.Text会在a[m,j]中。其次,a 是 [1,1] 并且您正在尝试访问 a[1, bigger then 1] 因此出现错误。只需制作一个 new string[1,7].