繁体   English   中英

向DataGridView添加行,仅显示一行?

[英]Adding Rows To DataGridView, only one row shows up?

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;
}

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

您可以尝试使用Add中的索引,以防它在排序方面起了关键作用:

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

或更好:

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

您可以尝试看看是否可行吗?

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

您的索引不变。 您将dataGridMain.Rows.Count -1声明为索引

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

int n = dataGridMain.Rows.Add();

//now use n

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

//more code

dataGridMain.Rows.Add(); 这是将行添加到底部还是将其添加到第一行。 如果在开始时将其添加,则您只是在添加新记录,而一直在更新同一记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM