VB.NET WinForm中DataGridView刷新方法及新增行仅显最后一行问题
Let's break down why your current code isn't working as expected first:
When you use gridview.RowCount = gridview.RowCount + 1 to add a new row, the newly created row is always the last row in the DataGridView (its index equals gridview.RowCount - 1). But in your loop, you're assigning values to gridview.Row(i)—this means for early iterations, you're overwriting existing rows instead of populating the new ones. By the end of the loop, only the final assignment is visible, which is why you only see the last row.
Here are two reliable fixes to resolve this:
Solution 1: Use Rows.Add() to Directly Add and Populate New Rows
This is the most straightforward and recommended approach. The Rows.Add() method returns a reference to the newly created row, so you can immediately set its cell values without guessing indexes:
Dim i As Integer = 0 While i < 10 ' Add a new row and get its reference Dim newRow As DataGridViewRow = gridview.Rows.Add() ' Assign value to the first cell of the new row newRow.Cells(0).Value = i i += 1 End While
Solution 2: Correctly Target the New Row When Using RowCount
If you prefer sticking with modifying RowCount, make sure you always target the last row (the one you just added) instead of using the loop variable i directly:
Dim i As Integer = 0 While i < 10 gridview.RowCount = gridview.RowCount + 1 ' The new row is at index RowCount - 1 (since indexes start at 0) gridview.Rows(gridview.RowCount - 1).Cells(0).Value = i i += 1 End While
Refreshing the DataGridView (If Needed)
In most cases, the DataGridView will automatically refresh when you add rows and set cell values. But if you ever run into a scenario where the view doesn't update, you can force a refresh with:
gridview.Refresh()
Or invalidate the control to trigger a full redraw:
gridview.Invalidate()
内容的提问来源于stack exchange,提问作者Praveen Kumar s

