我有以下变量和数组。我正在尝试将值推送到ListView中以显示它们。
int oneLIAR = 0;
int twoLIAR = 0;
int threeLIAR = 0;
int fourLIAR = 0;
int fiveLIAR = 0;
int sixLIAR = 0;
int sevenLIAR = 0;
int eightLIAR = 0;
int nineLIAR = 0;
int tenplusLIAR = 0;
string[,] rowsViewLossCount = new string[10, 2] {
{"1", oneLIAR.ToString("#,##0")},
{"2", twoLIAR.ToString("#,##0")},
{"3", threeLIAR.ToString("#,##0")},
{"4", fourLIAR.ToString("#,##0")},
{"5", fiveLIAR.ToString("#,##0")},
{"6", sixLIAR.ToString("#,##0")},
{"7", sevenLIAR.ToString("#,##0")},
{"8", eightLIAR.ToString("#,##0")},
{"9", nineLIAR.ToString("#,##0")},
{"10+", tenplusLIAR.ToString("#,##0")}
};
当我尝试以下循环时,出现错误:
for (int i = 0; i < (rowsViewLossCount.Length-1); i++)
{
listViewLossCount.Items.Add(rowsViewLossCount[i, 0]).SubItems.Add(rowsViewLossCount[i, 1]);
}
我收到错误“IndexOutOfRangeException未处理”,“索引超出了数组的范围。”在错误发生时,i = 10,这意味着它超出界限,因为它应该只能到达9.但是,我尝试将我的for循环替换为“i&lt; 5”无效。有什么想法吗?
答案 0 :(得分:1)
嗯,你知道伯爵,所以你为什么不这样做呢?
for (int i = 0; i < 10; i++)
{
listViewLossCount.Items.Add(rowsViewLossCount[i, 0]).SubItems.Add(rowsViewLossCount[i, 1]);
}
或者:
for (int i = 0; i <= rowsViewLossCount.GetUpperBound(0); i++)
{
listViewLossCount.Items.Add(rowsViewLossCount[i, 0]).SubItems.Add(rowsViewLossCount[i, 1]);
}
答案 1 :(得分:1)
对于多维数组,您需要分别询问每个维度的长度:
GetLength(0)给出第一个维度,GetLength(1)得到第二个维度。你的循环应该是:
for (int i = 0; i < rowsViewLossCount.GetLength(0); i++)
{
listViewLossCount.Items.Add(rowsViewLossCount[i, 0]).SubItems.Add(rowsViewLossCount[i, 1]);
}