1

I need my to fill my datagridview with values from some list. I try to make it in such way:

List<List<object>> objList1 = new List<List<object>>
    {
         new List<object> {null, null, null, "Some Value"},
         new List<object> {"Some text", "Another Text", 212}
    };

List<List<object>> objList2 = new List<List<object>>
    {
         new List<object> {null, null, null, "Some Value from 2 list"},
         new List<object> {"Some text 3", "Another Text 5", 34}
    };

foreach (var objList in objList1)
    {
         dataGridView.Rows.Add();
         for (int i = 0; i < objList.Count -1; i++)
         {
              dataGridView.Rows[dataGridView.RowCount - 1].Cells[i].Value = objList[i] != null ? objList[i].ToString() : "";
         }
    }
    dataGridView.Rows.Add();

foreach (var objList in objList2)
    {
         dataGridView.Rows.Add();
         for (int i = 0; i < objList.Count - 1; i++)
         {
             dataGridView.Rows[dataGridView.RowCount - 1].Cells[i].Value = objList[i] != null ? objList[i].ToString() : "";
         }
    }
    dataGridView.Rows.Add();

But instead of getting my datagridview filled, I get only the last row filled:

enter image description here

4

1 回答 1

1

但是我的datagridview填充了我只填充了最后一行

您将AllowUserToAddRow属性设置为true. 所以当你写的时候:

dataGridView.Rows[dataGridView.RowCount - 1]

每次添加新行时,您都可以访问被“替换”的新行。应该改为

dataGridView.Rows[dataGridView.RowCount - 2]

请注意,该dataGridView.Rows.Add()方法为您提供了添加行的索引。所以你也可以写:

int addedRowindex = DataGridView.Rows.Add();
DataGridView.Rows[addedRowindex].Cells[i].Value = ...

我不确定您要完全理解您要做什么。如果我用 替换RowCount - 1RowCount - 2我得到:

在此处输入图像描述


for (int i = 0; i < objList.Count -1; i++)

不应该

for (int i = 0; i <= objList.Count - 1; i++) 

结果:

在此处输入图像描述

于 2013-10-02T01:57:41.173 回答