1

试图将所有文本框值放入一维、二维数组

http://content.screencast.com/users/TT13/folders/Jing/media/7689e48c-9bd6-4e22-b610-656b8d5dcaab/2012-07-06_0347.png

int[] xMatrix = new int[6], yMatrix = new int[6];
            int[,] aMatrix = new int[6, 6], bMatrix = new int[6, 6], cMatrix = new int[6, 6];

            foreach (Control control in this.Controls)
            {
                if (control is TextBox)
                {
                    string pos = control.Name.Substring(1);
                    if (control.Name.StartsWith("a"))
                    {
                        int matrixPos = Convert.ToInt32(pos);
                        int x = matrixPos / 10;
                        int y = matrixPos % 10;
                        aMatrix[x, y] = Convert.ToInt32(control.Text);
                    }
                    else if (control.Name.StartsWith("b"))
                    {
                        int matrixPos = Convert.ToInt32(pos);
                        int x = matrixPos / 10;
                        int y = matrixPos % 10;
                        bMatrix[x, y] = Convert.ToInt32(control.Text);
                    }
                    else if (control.Name.StartsWith("c"))
                    {
                        int matrixPos = Convert.ToInt32(pos);
                        int x = matrixPos / 10;
                        int y = matrixPos % 10;
                        cMatrix[x, y] = Convert.ToInt32(control.Text);
                    }
                    else if (control.Name.StartsWith("x"))
                    {
                        int arrayPos = Convert.ToInt32(pos);
                        xMatrix[arrayPos] = Convert.ToInt32(control.Text);
                    }
                    else if (control.Name.StartsWith("y"))
                    {
                        int arrayPos = Convert.ToInt32(pos);
                        yMatrix[arrayPos] = Convert.ToInt32(control.Text); // <== ERROR LINE
                    }
}

收到错误信息

在此处输入图像描述

这里有给定的值

在此处输入图像描述

我错过了什么?

4

3 回答 3

2

我认为你在 arrayPos 中获得了价值>= 6,这就是你得到这个异常的原因,因为yMatrix它被定义为一个包含 6 个元素的数组。

int arrayPos = Convert.ToInt32(pos);

这里 pos 来自 string pos = control.Name.Substring(1);,放一个调试器,看看你得到了什么值pos

于 2012-07-06T05:22:20.357 回答
1

当这条线运行时:

int arrayPos = Convert.ToInt32(pos);

它可能导致 arrayPos 为 6(猜测数据不足)。

数组是基于 0 的,这意味着您的数组的有效索引是 0 到 5。我敢打赌您的控件被命名为 1 到 6...

如果是这种情况,请从 arrayPos 中减去 1 以将范围 1..6 转换为范围 0..5。

int arrayPos = Convert.ToInt32(pos) - 1;
于 2012-07-06T05:26:46.673 回答
0

似乎有一些名称以“y6”-“y9”开头的文本框(或派生控件)。检查您的 ...designer.cs 文件应该有助于找到那个文件。

或者你可以离开那条危险的道路,使用你的变量名来存储参数。相反,您可以使用 TextBoxes 的 Tag-Property 来存储相应的坐标。这将使事情变得更清晰,更不容易受到攻击。

于 2012-07-06T05:32:31.657 回答