winforms 一次将三个文本文件添加到三个datagridview中

o75abkj4  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(85)

我想加载三个文本文件到三个datagridviews一次后,我都选择了它在我的文件夹中。我想它自动加载三个文本文件,我突出显示到三个datagridviews一起。我已经在我的表单中使用VB.NET创建。

Private Sub PictureBox1_Click_1(sender As Object, e As EventArgs) Handles PictureBox1.Click
     If OpenFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK _
Then
          DataGridView1.Rows.Clear()
          For Each Line In My.Computer.FileSystem.ReadAllText(OpenFileDialog1.FileName).Split(Environment.NewLine)
              DataGridView3.Rows.Add(Split(Line, ControlChars.Tab))
              DataGridView2.Rows.Add(Split(Line, ControlChars.Tab))
              DataGridView1.Rows.Add(Split(Line, ControlChars.Tab))
          Next

     End If
End Sub

字符串

gk7wooem

gk7wooem1#

您需要遍历OpenFileDialog返回的文件数组。
此外,最好将代码分割成更小的单元,因为这样更容易调试和维护。
我在一个表单上放置了一个按钮和三个DataGridView控件,并使用了以下代码:

Imports System.IO

Public Class Form1

    Function GetDataFiles() As String()
        Using ofd As New OpenFileDialog() With {.InitialDirectory = "C:\Temp",
                                                .DefaultExt = ".csv",
                                                .Multiselect = True,
                                                .Title = "Select 3 files"}

            If ofd.ShowDialog = DialogResult.OK Then
                Return ofd.FileNames
            End If

        End Using

        Return Array.Empty(Of String)

    End Function

    Sub LoadData()
        Dim nFiles = 3

        Dim srcFiles = GetDataFiles().Take(nFiles)

        If srcFiles.Count <> nFiles Then
            ' Probably need to ask user to select nFiles files.
            Exit Sub
        End If

        'TODO: Maybe find a better way of getting the DGVs.
        Dim dgvs = {DataGridView1, DataGridView2, DataGridView3}

        For i = 0 To nFiles - 1
            'TODO: Possibly read the files first to get the number of columns.
            Dim nCols = 4
            Dim dt = New DataTable()
            For j = 1 To nCols
                dt.Columns.Add($"DT{i}-Col{j}")
            Next

            Dim data = File.ReadAllLines(srcFiles(i)).Where(Function(s) Not String.IsNullOrEmpty(s))

            For Each s In data
                dt.Rows.Add(s.Split(ControlChars.Tab))
            Next

            dgvs(i).DataSource = dt

        Next

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        LoadData()

    End Sub

End Class

字符串
获取:


的数据
如果你已经将一个OpenFileDialog放到了窗体上,那么你需要选择它,按F4进入它的属性,然后在“行为”部分将“多选”属性改为“真”。

相关问题