简体   繁体   中英

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:

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

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(); 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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