Referencing an object(RichTextBox more precisely) from within a class.


I would like to pass an object to a class through the constructor so that every function from that class has access
to that object. More specifically, I would like to have control over a RichTextBox from my custom class so that I don't have to
pass the object as argument everytime I use a function from my class.

Thank you!
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Declare a class level variable to store the textbox.  If needed you can use WithEvents and sink events for the RichTextBox...  If needed we can show you how.

Public Class MyRTBClass
    Private mRichTextBox As RichTextBox
    Public Sub New(ByVal RTB As RichTextBox)
        mRichTextBox = RTB
    End Sub
    'Sub/function that uses class level variable.
    Public Function GetText() As String
        Return mRichTextBox.Text
    End Function
End Class

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
PatricePaquetteAuthor Commented:
This is exactly what I wanted, thanks alot.
I was under the impression that this wouldn't work because it would only copy the object and not
actually reference it. I guess I was wrong.
>because it would only copy the object

Actually, it makes a copy of the variable that references the RichTextBox.  Think of object variables as references to object instances.  Setting one object variable = to another only makes another copy of the reference.  There is still only a single instance.

Dim x, y as MyClassThingy  'Two object references
x = new MyClassThingy       'New instance of the object.
y = x                                    'Both object references point to the same instance.
PatricePaquetteAuthor Commented:
Thank you very much for clearing this up for me.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.