0

我有一个我创建的示例代码。但是,当我运行时,我得到一个超出范围的错误,并且似乎找不到原因。

List<int> list1 = new List<int>() { 1, 2, 3, 4 };
List<string> list2 = new List<string>() { "a", "b", "c", "d", "e" };
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AutoGenerateColumns = false;
int myRow = -1;
int myCell = -1;
foreach (var i in list1)
    {
     myRow = myRow+1;
     foreach (var d in list2)
     {
          myCell = myCell+1;

          dataGridView1.Rows[myRow].Cells[myCell].Value = i + " and " + d; 
     }
}

我会很感激任何帮助。谢谢!

4

4 回答 4

3

您需要在第二次 foreach 之后设置您的myCell背部。-1

在 foreach 中也添加您的行,因为您无法选择不存在的行。

现在一直在涨

int myRow = -1;
int myCell = -1;
foreach (var i in list1)
{
 myRow = myRow+1;
//add the row here
 foreach (var d in list2)
 {
      myCell = myCell+1;
      //add the cell here

      dataGridView1.Rows[myRow].Cells[myCell].Value = i + " and " + d; 
 }
myCell = -1;
}

甚至更好的是设置myRow和初始化并myCell0循环结束时增加它们。

IE

int myRow = 0;
foreach(var i in list1) {
//DO YOUR STUFF
myRow++;
}
于 2013-07-18T11:08:44.283 回答
2

或使用简单的for循环:

for(int row = 0; row < list1.Count(); row++)
{
    for(int cell = 0; cell < list2.Count(); cell++)
    {
         dataGridView1.Rows[row].Cells[cell].Value = i + " and " + d; 
    }
}
于 2013-07-18T11:13:25.557 回答
1

这是适合您的解决方案。这也是经过测试的。

List<int> list1 = new List<int>() { 1, 2, 3, 4 };
            List<string> list2 = new List<string>() { "a", "b", "c", "d", "e" };
            dataGridView1.AllowUserToAddRows = true;
            dataGridView1.AutoGenerateColumns = false;
            int myRow = -1;
            int myCell = -1;
            foreach (var i in list1)
            {
                myRow = myRow + 1;
                foreach (var d in list2)
                {
                    myCell = myCell + 1;
                    if(dataGridView1.Rows.Count==1)
                        dataGridView1.Rows.Add(list1.Count);
                    dataGridView1.Rows[myRow].Cells[myCell].Value = i + "and" + d;
                }
                myCell = -1;
            }

不要忘记标记为答案

注意:第一行将是此处的标题。

于 2013-07-18T11:56:07.397 回答
0

首先将行添加到gridview,然后你可以填充它的值。

于 2013-07-18T11:07:51.227 回答