使用vb.net从文本文件轻松快速地加载100k行的数据网格

时间:2016-08-12 06:23:47

标签: vb.net datagrid vb.net-2010

我有一个用VB.net创建的程序,其中文本文件用于加载datagrid,但它很慢,有很多代码,当有很多行从文本文件导入时。

有没有更简单的方法对此进行编码,因此数据网格加载速度不是很慢?

Private Sub Load_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Load.Click

OpenFileDialog1.Filter = "Text Files|*.txt|All Files|*.*"
    OpenFileDialog1.Title = "Select Text File for Path"
    OpenFileDialog1.FileName = "Select File"
    If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.Ok Then
        txttblnm.Text = OpenFileDialog1.FileName
        txtfilenm.Text = System.IO.Path.GetFileName(txttblnm.Text)
        txtfilenm.Text = txtfilenm.Text.Substring(0, txtfilenm.Text.Length - 4)
        Label7.Text = System.IO.Path.GetDirectoryName(txttblnm.Text)
    End If

    If Len(txtfilenm.Text) = 8 And CheckBox1.CheckState = CheckState.Checked Then
        Dim textfiles() = Directory.GetFiles(Label7.Text, "*.txt")
        For Each file As String In textfiles
            Call dgv1_load()
            Call Access_export()
            Call clear_item()
        Next
    ElseIf Len(txtfilenm.Text) >= 9 Then
        MsgBox("Please Load DATA", MsgBoxStyle.Information, "Load Data Error")
        Exit Sub
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

您与用户界面的互动太多了。与gridview +文本框的每次交互都很昂贵。

您应该做的是首先创建一个DataTable并用行数据填充它。

然后在全部加载之后将datagridview.DataSource设置为此表,所有内容只会被绘制一次。

    Private Function ParseFile(filename As String) As DataTable
        Dim result As New DataTable()
        result.Columns.Add("colname 1 ....")
        result.Columns.Add("colname 2 ....")

        Using inputFile As New StreamReader(filename) 'Open text file

            Do Until inputFile.EndOfStream
                Dim row = result.Rows.Add()
                row(0) = "blah"
            Loop
        End Using
        return result
    End Function

    Private Sub ShowResult()
        dgv1.DataSource = ParseFile(filename)
    End Sub