0
votes

what i need is when form2 is opened from form1 cliking on a button then on form2 i click on anothe butto and i set the value of a textbox of form1.

if i set the type of application as windows form application it is all ok but if i set as class library i have the error reference to a non-shared member requires an object reference.

if i reference to Dim frm = New form2 it open a second form2 and i dont want it.

how can resolve this?

thank you.

here is the code:

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Form2.ShowDialog()
End Sub
End Class


Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Form1.TextBox1.Text = "aaaa"
    Me.Close()

End Sub
End Class
2

2 Answers

0
votes

When you build vb.net winforms project, some extra code is generated in the project. For example static instance of the Form class, so you can access instance methods through the class name Form1.ShowDialog().

This were done for VB6 programmers to make shifting from VB to VB.NET easier.

When you change project to be a library project, this code not generated anymore and Form1 is just a class and you can not access instance methods directly, but need to instantiate an instance "manually".

Instead of using this "hidden" shared instance, create form instances manually. You can pass instance of form1 to the constructor of form2 and update form1 from there.

Because you are using ShowDialog, I would suggest to make Form2 not depend on the Form1 and instead of updating Form1 textbox directly(you would like to avoid making Form controls public), return value as result of the dialog.

Public Class Form2
  Public Property ResultValue As String

  Private Sub Button1_Click(s As Object, e As EventArgs) Handles Button1.Click
    ResultValue = "Value from Form 2";
    DialogResult = DialogResult.OK; ' This suppose to close the form
  End Sub
End Class

Public Class Form1
  Private Sub Button1_Click(s As Object, e As EventArgs) Handles Button1.Click
    Using form As New Form2()
      Dim result As DialogResult = form.ShowDialog()
      If result = DialogResult.OK Then
        TextBox1.Text = form.ResultValue
      End If
    End Using
  End Sub
End Class
-1
votes

Add the following to form1

Public static sub changeTitle(myTextBox as Object,title as string)
myTextBox.Text=title
End sub

Call above function in form2

Form1.changeTitle(Form1.TextBox1, "new title")