我是这个论坛的新手。这是我的第一篇文章,尽管我在这里花了很多时间寻找答案。
我已经在Excel中使用了VBA多年了,但是最近开始在Visual Studio 2015中使用VB。我创建了Form 1作为Mdicontainer,并在其中打开了另一种形式。此表单(formxyz)包含一个datagridview。
form1有一个menustrip,我当前正在尝试编写代码时,当选择了其中一个菜单项,以从CSV填充DGV。在此阶段,我只是想读取数据,然后我将处理代码以将字符串拆分。
屏幕截图
我选择要导入的文件没有问题,而流程阅读器似乎可以读取该文件,但是没有数据将其列入DGV。
当我尝试将代码放在formxyz上以进行按钮点击事件时,填充了DGV。因此,我相信错误是由于我引用DGV的方式,因为Menustrip_click事件的代码在Form1上,但DGV在Formxyz上。
如果有人可以指出我出错的地方,我会很感激。我的代码如下所示。
谢谢Tepede
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim FormXYZ As New FormXYZ()
FormXYZ.MdiParent = Me 'Set the Parent Form of the Child window.
FormXYZ.Show() 'Display the XYZ form.
End Sub
'-------------------------------------
'StripMenu click command to import CSV
Public Sub TSMIFileImportCSV_Click(sender As Object, e As EventArgs) Handles TSMIFileImportCSV.Click
Dim Filename As String
Dim RowValue As String
Dim OpenFile As OpenFileDialog = New OpenFileDialog()
'Open file dialog
With OpenFile
.Filter = "CSV (*.CSV)|*.csv"
.FilterIndex = 1
.InitialDirectory = "C:"
.Title = "Open File"
.CheckFileExists = False
End With
If OpenFile.ShowDialog() = DialogResult.OK Then
Filename = OpenFile.FileName
End If
'---------
' Read CSV file content
Dim objReader As StreamReader = New StreamReader(Filename)
While objReader.Peek() <> -1
RowValue = objReader.ReadLine()
'Fist column is Boolean, the second should have the data from the CSV file
FormXYZ.DataGridView1.Rows.Add(True, RowValue, "Test", "Test")
End While
objReader.Close()
End Sub
看起来您正在将实例丢给您显示的formxyz,因为其定义为"表单负载"。将该变量的范围扩展到班级级别。
Public Class Form1
Private FormXYZ As FormXYZ
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FormXYZ = New FormXYZ()
FormXYZ.MdiParent = Me 'Set the Parent Form of the Child window.
FormXYZ.Show() 'Display the XYZ form.
End Sub