首页 > 解决方案 > Update Textbox after each iteration VB.Net WPF

问题描述

I have a For loop which runs through xlsx files in a directory, I need to append the filenames in a TextBlock after each loop and refresh the TextBlock to show the updated text.

The code I have below only displays the filenames after the loop has executed.

 Dim lcFileName As String = ""
 Dim fileArray() As String = Directory.GetFiles(txtDirectory.Text, "*.xlsx", SearchOption.AllDirectories)

    For Each file As String In fileArray

        Dim ExcelApp As Excel.Application = New Excel.Application
        Dim Workbook As Excel.Workbook = ExcelApp.Workbooks.Open(file)
        Dim Worksheet As Excel.Worksheet = Workbook.Sheets(1)
        Dim Range As Excel.Range = Worksheet.UsedRange

        Dim rowCount As Integer = Range.Rows.Count
        Dim colCount As Integer = Range.Columns.Count

        Dim tmpOrder(rowCount, colCount) As String
        tbResults.Text = tbResults.Text + Environment.NewLine + Path.GetFileName(file) + " imported."

        For i = 1 To rowCount
            For j = 1 To colCount
                'New line
                If (i = 1 And j = 1) Then
                    tmpOrder(i - 1, j - 1) = Range.Cells(i, j).Value
                    lcFileName = tmpOrder(i - 1, j - 1).ToString()

                Else

                    If (Not String.IsNullOrEmpty(Range.Cells(i, j).Value)) Then
                        tmpOrder(i - 1, j - 1) = Range.Cells(i, j).Value.ToString()
                    End If
                End If
            Next
        Next

        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Worksheet)
        Worksheet = Nothing
        ExcelApp.ActiveWorkbook.Close(True)
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Workbook)
        Workbook = Nothing
        ExcelApp.Quit()
        System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelApp)
        ExcelApp = Nothing
        '
    Next

Any help would be appreciated, VB.Net required.

标签: wpfvb.netfor-loop

解决方案


终于让它工作了。好的,首先我创建了我的方法来使用为文件名传递的参数更新 TextBlock。

Public Sub UpdateResults(ByVal lcFile As String)
    tbResults.Text = tbResults.Text + Environment.NewLine + Path.GetFileName(lcFile) + " imported."
End Sub

在我的 For 循环中,我使用以下代码调用了该方法

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New ThreadStart(Sub() Me.UpdateResults(lcFile)))

其中 UpdateResults(lcFile) 是传递的方法和参数。

如果您没有传递任何参数,则使用它调用您的方法,其中“MyMethod”是您要运行的方法的名称。

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New ThreadStart(AddressOf MyMethod))

推荐阅读