VB.NET: What is the best way to get the value from the second form?

I teach myself VB.Net.

Here is a problem I recently ran into. Let's say I have the main Form1 in my application. Form1 calls the second LoginForm, which (for example, the name suggests) is a login window with the username and password fields. The expected behavior is that LoginForm will record login information and pass it to Form1.

What is the best way to do this?

In my mind, I thought of the lines of a function call, such as "doLogin", which "showed" LoginForm, fixed the data entered, deleted the form and returned the login data (possibly in some kind of bean). Somehow I do not see this as an opportunity

I'm currently less elegant. LoginForm is displayed Form1 modally (i.e. ShowDialog); the link "me" is passed to the second window. After user input has been received in LoginForm, I set the value to Form1 and then delete.

Is that how everyone does it?

+3
source share
3 answers

I always passed the delegate to the second form, which can be called to "return" the values ​​from the second form to the first.

This way you avoid tight communication.

Classic observer pattern.


An example implementation is as follows:

Form1. Click1 Form1 Form2 Form1. Form2 :

'Form1.vb
Public Delegate Sub delPassData(ByVal text As TextBox)

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
  Dim frm As Form2 = New Form2
  Dim del As delPassData = New delPassData(AddressOf frm.funData)
  del(Me.textBox1)
  frm.Show()
End Sub

Form2 , . textBox1 label1.

'Form2.vb
Public Sub funData(ByVal text As TextBox)
  label1.Text = text.Text
End Sub

Form1, funData , .

+1

#, : #, ?

+2

VB.NET "My.Forms"

LoginForm .

Me.RetrievedDataTextBox.Text = My.Forms.LoginForm.Textbox1.Text
0

Source: https://habr.com/ru/post/1706295/


All Articles