Michael harris
Michael harris

Reputation: 996

VB.NET Classes trouble

I have a form that contains an object "TextBox1" (TextBox1 control)

In the code section I've initialized a new TextBox object that is not on the form like this:

  Dim aa As New TextBox
  aa = TextBox1 'THE CONTROL ON THE FORM
  aa.Text = "hi how are you?"

The TextBox1 on the form is now changed it wrote "hi how are you?"

shouldn't be the "aa" object and the "TextBox1" be separate one from another? means that changing one object wouldn't affect the other?

Why this happens? And how to prevent this?

Means Separating the objects one from another.

Writing the code at this form

Public Sub blah(ByVal aa As TextBox)
    aa.Text = "hi how are you?"
End Sub

And then calling the sub by

    blah(TextBox1)

Doesn't solve the problem.

Upvotes: 0

Views: 66

Answers (3)

Meta-Knight
Meta-Knight

Reputation: 17875

As far as I know there is no easy way to clone a TextBox but if you want to do this, you can just copy over the relevant properties:

Dim aa As New TextBox
aa.Text = TextBox1.Text
'Copy over other relevant properties here
aa.Text = "hi how are you?"

LarsTech raises a good question though. Do you really need to clone the whole textbox? Wouldn't it be sufficient to just copy over the text?

Also note that the code that you posted doesn't do what you think it does. By doing something like:

Dim aa As New TextBox
aa = TextBox1

You're first assigning the aa variable to a newly created textbox, then you're re-assigning this variable to the existing TextBox1. You've just lost your reference to the newly created textbox.

Upvotes: 0

CamelSlack
CamelSlack

Reputation: 573

When you set an object equal to another, in this case aa to TextBox1, aa is now a pointer to TextBox1 and any actions made to it will affect both.

A way to use it as just the value would be to use the instance in a function. As such.

Public Sub process(ByVal aa as Object)

'do stuff
End Sub

Upvotes: 0

SLaks
SLaks

Reputation: 888185

.Net objects are passed by reference.
aa and TextBox1 both refer to the same TextBox instance.

You can manually create a copy of an instance by copying over its properties to a different instance.

Upvotes: 1

Related Questions