简体   繁体   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;
}

When I run the loop above, it adds all of the rows but only the last row contains any data. 当我运行上面的循环时,它将添加所有行,但只有最后一行包含任何数据。 What am I doing wrong? 我究竟做错了什么?

You could try using the index from Add in case it is doing something hokey with ordering: 您可以尝试使用Add中的索引,以防它在排序方面起了关键作用:

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

Or better: 或更好:

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

Can you try and see if this works? 您可以尝试看看是否可行吗?

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

Your index doesnt change. 您的索引不变。 You state dataGridMain.Rows.Count -1 as an index 您将dataGridMain.Rows.Count -1声明为索引

It looks like the count does not change, it appears you need to grab the index first, store it in a variable and then add the values: 看起来计数没有变化,您需要首先获取索引,将其存储在变量中,然后添加值:

int n = dataGridMain.Rows.Add();

//now use n

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

//more code

dataGridMain.Rows.Add(); dataGridMain.Rows.Add(); Does this adds the rows to bottom or adds it to the first. 这是将行添加到底部还是将其添加到第一行。 If it adds it at the begininning then you are just adding new record but updating the same record all the time. 如果在开始时将其添加,则您只是在添加新记录,而一直在更新同一记录。

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

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