提问人:AYANWALE LUKMON 提问时间:11/5/2023 最后编辑:derloopkatAYANWALE LUKMON 更新时间:11/5/2023 访问量:79
一次将三个文本文件添加到三个数据网格视图中
Add three text file into three datagridview at once
问:
我想在我的文件夹中选择三个文本文件后,一次将三个文本文件加载到三个数据网格视图中。我希望它自动将我突出显示的三个文本文件加载到三个数据网格视图中。我使用 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
答:
2赞
Andrew Morton
11/5/2023
#1
您需要循环访问 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 拖放到窗体上,则需要选择它,按 进入其属性,然后在“行为”部分中将“Multiselect”属性更改为“True”。F4
评论
0赞
AYANWALE LUKMON
11/6/2023
该解决方案不适用于我的项目,我现在必须跳过它,以便我可以继续项目的下一阶段
0赞
Andrew Morton
11/6/2023
@AYANWALELUKMON 它只是代码片段的集合,您可以选择适合您的项目所需的部分。哪个部分不适用于您的项目?
0赞
AYANWALE LUKMON
11/11/2023
任何人都可以帮助我使用 vb.net 进行autocad设计吗
0赞
Andrew Morton
11/11/2023
@AYANWALELUKMON 请阅读 我如何提出一个好问题?
评论
OpenFileDialog
DataGridViews
FileNames
属性,这正是你所需要的。OpenFileDialog