应用程序在创建datagridview时冻结

时间:2015-06-30 21:50:40

标签: vb.net datagridview

我使用以下代码将Excel文件读入datagridview(EquipmentDataGrid)。它第一次构建datagridview时效果很好,但是,如果我导航回标签页(因而重新运行代码),它会冻结并花费大约10分钟让UI变得响应。我无法弄清楚问题是什么,因为它一开始就能正常工作。我对编程非常陌生(刚开始大约1周以​​前没有经验)很抱歉,如果这是一个简单的修复。

Private Sub TabControl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged

    If TabControl1.SelectedTab Is Equipment Then
        Dim xlApp As Excel.Application
        Dim xLBook As Excel.Workbook
        Dim xLSheet As Excel.Worksheet
        Dim x As Integer

        EquipmentDataGrid.Rows.Clear()
        EquipmentDataGrid.Columns.Clear()

        xlApp = New Excel.Application


        xLBook = xlApp.Workbooks.Open(My.Settings.SharefilePath + "Equipment Moves\EquipmentLog")
        xLSheet = xLBook.Worksheets("Summary")

        EquipmentDataGrid.ColumnCount = 5
        EquipmentDataGrid.Columns(0).Name = "Date"
        EquipmentDataGrid.Columns(1).Name = "Equipment Number"
        EquipmentDataGrid.Columns(2).Name = "Description"
        EquipmentDataGrid.Columns(3).Name = "Hours"
        EquipmentDataGrid.Columns(4).Name = "Location"


        For x = 1 To xLSheet.Range("F1").Value
            EquipmentDataGrid.Rows.Add()
            EquipmentDataGrid.Item(0, x - 1).Value = xLSheet.Cells(1 + x, 1).Text
            EquipmentDataGrid.Item(1, x - 1).Value = xLSheet.Cells(1 + x, 2).value
            EquipmentDataGrid.Item(2, x - 1).Value = xLSheet.Cells(1 + x, 5).value
            EquipmentDataGrid.Item(3, x - 1).Value = xLSheet.Cells(1 + x, 3).value
            EquipmentDataGrid.Item(4, x - 1).Value = xLSheet.Cells(1 + x, 4).value
        Next
        xLBook.Saved = True
        xLBook.Close()
        xlApp.Quit()
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xLBook)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xLSheet)

        x = Nothing
        xLBook = Nothing
        xLSheet = Nothing
        xlApp = Nothing

        GC.Collect()
        GC.WaitForPendingFinalizers()
        GC.Collect()
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

如果问题仅在第一次运行后运行,我的猜测是清除网格是问题。就像JabberWocky建议的那样,在清除网格的线条之前粘贴一个断点,然后在一条线之后粘贴一个断点,这样你就可以了解该步骤需要多长时间。

如果这是问题,那么问题似乎没有多少办法。您可以将清除行包装在某些逻辑中,以便在Excel文件中的数据与网格中的数据匹配时不会运行它们,但如果要加载新的/更改的数据,这将无济于事。