多维数组的indexoutofrangeexception [英] indexoutofrangeexception with multidimensional arrays
问题描述
我开始在学校使用C#,遇到了问题...
我正在尝试使用以下代码创建带有按钮的数组:
Hi, i started working with C# in school and am having an issue...
i''m trying to make an array with buttons with folowing code:
public partial class Form1 : Form
{
private Button[,] _tabs;
private string[,] _tabsnaam = new string[,]
{
{"E4","F4","Fs4","G4","Gs4","A4","Bb4","B4","C5","Cs5","D5","Ds5","E5"},
{"B3","C4","Cs4","D4","Ds4","E4","F4","Fs4","G4","Gs4","A4","Bb4","B4"},
{"G3","Gs3","A3","Bb3","B3","C4","Cs4","D4","Ds4","E4","F4","Fs4","G4"},
{"D3","Ds3","E3","F3","Fs3","G3","Gs3","A3","Bb3","B3","C4","Cs4","D4"},
{"A2","Bb2","B2","C3","Cs3","D3","Ds3","E3","F3","Fs3","G3","Gs3","A3"},
{"E2","F2","Fs2","G2","Gs2","A2","Bb2","B2","C3","Cs3","D3","Ds3","E3"}
};
public Form1()
{
InitializeComponent();
maaktabs();
}
indexoutofrangeexception
indexoutofrangeexception
public void maaktabs()
{
int x, y;
_tabs = new Button[13,6];
//_tabsnaam = new string[13, 6];
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 6; j++)
{
_tabs[i, j] = new Button();
_tabs[i, j].Location = new System.Drawing.Point(x, y);
_tabs[i, j].Size = new System.Drawing.Size(5, 5);
_tabs[i, j].Text = _tabsnaam[ i, j];
Controls.Add(_tabs[i, j]);
}
}
}
当我尝试运行代码时,得到indexoutofrangeexception
致敬
N.D.
when i try to run the code i get indexoutofrangeexception
thx for the attention
N.D.
推荐答案
在此行:
_tabs = new Button[13,6];
您正在创建13行和6列.我想你的意思是相反的.
修订:
这可能会给您错误:
You are creating 13 rows and 6 columns. I think you mean to do the opposite.
Revision:
This is likely giving you the error:
_tabs[i, j].Text = _tabsnaam[ i, j];
_tabs有13行6列,而_tabsnaam有6行13列,因此复制循环将不起作用.
_tabs has 13 rows, 6 columns, while _tabsnaam has 6 rows, 13 columns, so the copying loop will not work.
在代码周围放置try/catch块是一个好主意.使用调试器是另一个好主意(至少可以确定执行的位置).除了这两个建议之外,请尝试使用null
s或实际的Button
对象初始化_tabs
数组.
Putting a try/catch block around the code is a good idea. Using the debugger is another good idea (at least then you can determine WHERE the execption is occurring). Beyond those two suggestions, try initializing the_tabs
array either withnull
s, or with actualButton
objects.
这篇关于多维数组的indexoutofrangeexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!