簡體   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