VBnet: Reference a form object from a class

蹲街弑〆低调 提交于 2021-01-29 10:46:47

问题


plan

im sure this question must have been answered somewhere because its pretty basic, but unfortunately I havent found the answer ...

My plan is to create a simple log function that uses a RichTextField as an output and implements functionalities like Add, AddLine, RemoveLine, ReplaceLine, ...

what doesnt work

whenever i try to access the RichTextBox object from within the log Class, i get a "is nothing" exception.

my approach

the idea was to store a reference to the RichTextBox in the class itsself, that is passed on creating a new class instance:

Public Class Log
    Dim _logBox As RichTextBox

    Public Sub New(ByRef logBox As RichTextBox)
        _logBox = logBox
    End Sub

    Public Sub AddLine(ByVal text As String)
        Me.Add(text)
        _logBox.AppendText(Environment.NewLine)
    End Sub
End Class

And in my Form class, a RichTextBox is created at startup and passed to the log Class:

Public Class Form1
    Dim log As New Log(RtbxLog) ' RtbxLog: RichTextBox object created on form

    [on some button click event]
      log.AddLine("entry with new line")  ' THIS CAUSES "nothing" EXCEPTION
End Class

回答1:


RtbxLog isn't initialized until the New is called. This is usually done during InitializeComponent(). I suggest you create your log after InitializeComponent is called (in the new).

Also, might I suggest you create your own control (that inherit from RichTextBox) instead. Or an other option is that your log class only store the information and the form takes care of display it in the textbox.



来源:https://stackoverflow.com/questions/52206783/vbnet-reference-a-form-object-from-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!