我是这个论坛的新手。这是我的第一篇文章,虽然我花了很多时间在这里寻找答案。
我已经在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
答案 0 :(得分:1)
看起来您正在丢失您显示的FormXYZ实例,因为它的定义在Form Load中。将该变量的范围扩展为类级别。
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