逐行填充DataGridView只会填充最后一行

时间:2015-05-13 18:43:37

标签: 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 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命令,我看到代码IS成功读取excel电子表格,所以这必须是一个显示的东西?我已经检查了大多数简单的显示选项,但是看起来没有改变?有人有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我非常确定您的datagridview将AllowUserToAddRows属性设置为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

如果您决定将AllowUserToAddRows更改为False,这两种方式仍然有用。