OnLoad Sub(Visual Basic)的问题

时间:2016-12-01 20:28:27

标签: vb.net function onload

我在启动时声明默认路径文件时遇到了一些麻烦。
每次我运行程序时,都会说pathFile为null。 有人知道我的代码需要更改什么吗?

Imports System
Imports System.IO
Imports System.Text

Public Class GlobalVariables
    Public Shared pathFile As String
End Class

Public Class Form1
    Protected Overridable Sub OnLoad(e As EventArgs)
        GlobalVariables.pathFile = My.Computer.FileSystem.SpecialDirectories.Desktop
    End Sub

    Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        ' create or overwrite the file
        Dim fs As FileStream = File.Create(GlobalVariables.pathFile)

        ' add text to file
        Dim info As Byte() = New UTF8Encoding(True).GetBytes(rtbText.Text)
        fs.Write(info, 0, info.Length)
        fs.Close()
    End Sub
End Class

提前致谢!
- Xaaf代码

1 个答案:

答案 0 :(得分:1)

我不会尝试覆盖OnLoadOverrides而不是Overridable),而是会处理加载事件:

Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    GlobalVariables.pathFile = My.Computer.FileSystem.SpecialDirectories.Desktop
End Sub

您可能只需设置声明pathFile的值:

Public Class GlobalVariables
    Public Shared pathFile As String = My.Computer.FileSystem.SpecialDirectories.Desktop
End Class