添加行到DataGridView,只显示一行?

时间:2011-01-07 20:11:40

标签: c# winforms datagridview

foreach (var a in A)
{
    dataGridMain.Rows.Add();
    dataGridMain.Rows[dataGridMain.Rows.Count - 1].Cells[0].Value = a.Date;
    dataGridMain.Rows[dataGridMain.Rows.Count - 1].Cells[1].Value = a.Value;
}

当我运行上面的循环时,它会添加所有行,但只有最后一行包含任何数据。我做错了什么?

4 个答案:

答案 0 :(得分:3)

你可以尝试使用Add中的索引,以防它正在做一些有关订购的事情:

var index = grid.Rows.Add();
grid.Rows[index].Cells[....

或更好:

var index = grid.Rows.Add();
var row = grid.Rows[index];
row.Cells[....
row.Cells[....

答案 1 :(得分:1)

你能试试看这是否有效吗?

foreach(var a in A)
{
  YourObject row = new YourObject(){a.Date, a.Value};
  dataGridMain.Rows.Add(row);
}

答案 2 :(得分:0)

您的索引没有变化。 您将dataGridMain.Rows.Count -1指定为索引

看起来计数没有改变,看来你需要首先获取索引,将其存储在变量中,然后添加值:

int n = dataGridMain.Rows.Add();

//now use n

dataGrid.Rows[n].Cells[0].Value = a.date;

//more code

答案 3 :(得分:0)

dataGridMain.Rows.Add();这是将行添加到底部还是将其添加到第一行。 如果它在开始时添加它,那么你只是添加新记录,但始终更新相同的记录。