Vb.net 逐行填充DataGridView只填充最后一行

Vb.net 逐行填充DataGridView只填充最后一行,vb.net,excel,datagridview,oledb,Vb.net,Excel,Datagridview,Oledb,我试图使用循环用一列整数填充datagridview。我很确定我的循环和excel引用是正确的,因为我在其他项目中使用过它,但它不会正确显示。代码如下: Dim da As OleDbDataAdapter Dim ds As DataSet xlWorkbook2 = xlApp.Workbooks.Open(FormFile) xlWsheet2 = xlWorkbook2.Sheets(sheetname) 'open c

我试图使用循环用一列整数填充datagridview。我很确定我的循环和excel引用是正确的,因为我在其他项目中使用过它,但它不会正确显示。代码如下:

Dim da As OleDbDataAdapter
        Dim ds As DataSet

        xlWorkbook2 = xlApp.Workbooks.Open(FormFile)
        xlWsheet2 = xlWorkbook2.Sheets(sheetname)

        'open connection to nit spreadsheet'
        Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & FormFile & """;Extended Properties=""Excel 12.0;HDR=YES;""")

        'Fill dataviewgrid1 with element symbols, string'
        da = New OleDbDataAdapter("select * from [" & sheetname & "$A13:A" & lrow & "]", cn)
        ds = New System.Data.DataSet
        da.Fill(ds)
        DataGridView1.DataSource = ds.Tables(0)

        'Fill dataviewgrid2 with compositions, integers'
        With xlWsheet2
            For xrow As Integer = 13 To lrow
                DataGridView2.ColumnCount = 1
                DataGridView2.Rows.Add()
                DataGridView2.Item(0, xrow - 12).Value = xlWsheet2.Cells(xrow, 2).Value
                Console.WriteLine(xlWsheet2.Cells(xrow, 2).Value)
            Next
        End With

所以dgv1填充很好,没有问题。Dgv2没有填充,或者说我得到了正确的行数,但只填充了最后一个单元格。因为我在那里有console.writeline命令,我看到代码正在成功地读取excel电子表格,所以这一定是一个显示的东西?我已经检查了大多数简易显示选项,但似乎什么都没有改变?有人有什么想法吗?

我很确定datagridview的
AllowUserToAddress
属性设置为
True
。如果是这样,每次使用
DataGridView2.Rows.Add()
,该行都会在最后一行之前添加;这是因为最后一行是用户用于手动向网格添加行的行。但在循环中,您总是编辑这一行

如果datagridview允许用户手动添加行,则必须设置从上一行到最后一行的值。一种更干净的方法是:

Dim index as Integer
With xlWsheet2
    DataGridView2.ColumnCount = 1
    For xrow As Integer = 13 To lrow
        index = DataGridView2.Rows.Add()
        DataGridView2.Item(0, index).Value = xlWsheet2.Cells(xrow, 2).Value
        Console.WriteLine(xlWsheet2.Cells(xrow, 2).Value)
    Next
End With
或者干脆

With xlWsheet2
    DataGridView2.ColumnCount = 1
    For xrow As Integer = 13 To lrow
        DataGridView2.Rows.Add(xlWsheet2.Cells(xrow, 2).Value)
        Console.WriteLine(xlWsheet2.Cells(xrow, 2).Value)
    Next
End With
(顺便说一句,在每个循环中不需要执行
DataGridView2.ColumnCount=1


如果您决定将
allowUserToAddress
更改为
False

Josh,太棒了!我可能找了一百万年都没找到。这就解决了问题。非常感谢!