System.ArgumentOutOfRangeException 发生在 mscorlib.dll C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8901061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
System.ArgumentOutOfRangeException occurred in mscorlib.dll C#
提问by Eduard Luca
I have a DataGridView which I am populating from a list of objects. However my the 2nd loop through my foreachresults in an ArgumentOutOfRangeException.
我有一个 DataGridView,我正在从对象列表中填充它。然而,我的第二次循环foreach在一个ArgumentOutOfRangeException.
Here is my code:
这是我的代码:
foreach (Abonat abonat in list.getAbonati())
{
dataGridView1.Rows[i].Cells[0].Value = abonat.id; //exception occurs here on second loop
dataGridView1.Rows[i].Cells[1].Value = abonat.prenume;
dataGridView1.Rows[i].Cells[2].Value = abonat.nume;
dataGridView1.Rows[i].Cells[3].Value = abonat.adresa;
i++;
}
The first time the foreachruns, everything is fine, it even shows up in the DataGridView, but the 2nd time, I get the exception (actually it says A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll) and my form is shown, without running the rest of the foreach.
第一次foreach运行时,一切都很好,它甚至出现在 DataGridView 中,但是第二次,我得到了异常(实际上它说mscorlib.dll 中发生了类型为“System.ArgumentOutOfRangeException”的第一次机会异常)和我的显示表单,而无需运行 foreach 的其余部分。
Any help on this? I've tried instancing the dataGridView1.Rows[i] = new DataGridViewRow();but it's read-only.
这有什么帮助吗?我试过实例化,dataGridView1.Rows[i] = new DataGridViewRow();但它是只读的。
采纳答案by legrandviking
You need to create rows before trying to access them;
在尝试访问它们之前,您需要创建行;
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = title;
dataGridView1.Rows[n].Cells[1].Value = dateTimeNow;
Then you'll be able to access them via dataGridView1.Rows[n].Cells[0].Value = x;
然后你就可以通过 dataGridView1.Rows[ n].Cells[0].Value = x;访问它们。
Cheers
干杯
回答by MethodMan
You can not add it this way. For starters it is not know or defined but then you increment it. You can add as many rows you want but you are adding them incorrectly is what we are trying to tell you.
您不能以这种方式添加它。对于初学者来说,它是不知道或定义的,但你可以增加它。您可以添加任意数量的行,但您添加的行不正确,这正是我们试图告诉您的。
incorrect usage here: dataGridView1.Rows[i].Cells[0].Value = abonat.id;
此处不正确的用法:dataGridView1.Rows[i].Cells[0].Value = abonat.id;
回答by Rouvé
Add the following above your code
在您的代码上方添加以下内容
dataGridView1.ColumnCount = 4; dataGridView1.ColumnHeadersVisible = true;
dataGridView1.ColumnCount = 4; dataGridView1.ColumnHeadersVisible = true;

