You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET WinForm中DataGridView刷新方法及新增行仅显最后一行问题

Fixing DataGridView Row Addition Issue in VB.NET WinForms

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:10:26