我在vb.net中创建一个简单的WinForm应用程序,它读取csv文件并在DataGridView组件中显示其内容。下面是我在主ui线程上运行的代码。
For Each line In fileinput
Dim elements = line.Split(",")
DataGridView1.rows.insert(0,elements)
Next
上面的代码在主窗体线程上运行正常。 elements数组用于填充每一行中的所有单元格,但如果我在一个单独的线程上尝试相同的代码,那么我在每行的第一个单元格中获得的是System.String []。有人知道为什么会这样吗?
以下是在新线程上创建和运行的整个代码:
Dim Filename As String =“”
Private Sub BtnCsv_Click(sender As Object, e As EventArgs) Handles BtnCsv.Click
Opf.ShowDialog()
Filename = Opf.FileName
Dim t As Thread
t = New Thread(AddressOf Me.ParseFileThread)
t.Start()
End Sub
Public Sub ParseFileThread()
'RtfOut.Text = Filename
'Read All Lines From The File since Its a csv
Dim inputFile() = File.ReadAllLines(Filename)
'The first line contains the headers for the csv file
Dim headers() = inputFile(0).Split(",")
SetGridHeaders(headers)
SetDataGrid(inputFile)
End Sub
Public Delegate Sub SetGridHeadersDelegate(ByVal headers As Array)
Public Sub SetGridHeaders(ByVal headers As Array)
If Dgv.InvokeRequired Then
Dgv.BeginInvoke(New SetGridHeadersDelegate(AddressOf SetGridHeaders), headers)
Else
For Each header In headers
Dgv.Columns.Add(header, header)
Dgv.Refresh()
Next
End If
End Sub
Public Delegate Sub SetDataGridDelegate(ByVal values As Array)
Public Sub SetDataGrid(ByVal values As Array)
If Dgv.InvokeRequired Then
Dgv.BeginInvoke(New SetDataGridDelegate(AddressOf SetDataGrid), values)
Else
For Each line In values
Dim cells = line.Split(",")
Dgv.Rows.Insert(0, cells)
Dgv.Refresh()
Next
End If
End Sub
答案 0 :(得分:1)
试试这个:
Me.Invoke(Sub()
DataGridView1.Rows.Insert(0, elements)
End Sub)
当您更改活动UI线程上的控件时,更改需要在该线程内部发生,否则您将遇到问题。我很惊讶代码执行时没有抛出异常。
Me.Invoke将确保在主线程上填充数据。