0
votes

How can i use the input received from a textbox in Form1 to make a connection with mySQL in form2. Now my program is like this:

Form1 opens and asks for Server, Username, Password. There are 3 buttons that will open different forms using form2 module, in form2 is the SQL connection string.

I have right now this at the connection string in form2:

Public Const cnString As String = "datasource=" & DBSelector.txtServer.Text & ";" _
                                  & "username=" & DBSelector.txtUsername.Text & ";" _
                                  & "password=" & DBSelector.txtPassword.Text & ";" _
                                  & "database=" & DBSelector.txtDatabase.Text & ";"

Now im stuck with this error: "Reference to a non-shared member requires an object reference." I'm new with Visual Basic, and i cant fix the problem. I think its because Form2 is a module and not a Public Class.

I hope someone can help me. Thanks in Advance!

1

1 Answers

0
votes
  1. To refer to another Form "in live", you must have a variable that it contains the instance of the second Form.

    For refernce a new Form from the Main-Form code, you can use the same variable which it was the Second-Form its created.

    In Your Case - reference from the called form to the caller form, you can 1. store the Forms instance in a static ariable in the Form itself, 2. pass it in parameter to Second Form constructor (the New() Sub).

    or you can skip all the topic by sending your information directly to the constructor, so:

    the Main-From Code - DBSelector in your case:

    Public Class DBSelector
    
        ...
    
        Public Sub LanchSecondForm()
            Dim form2 As Form2 = New Form2(txtServer.Text, _
                                           txtUsername.Text, _
                                           txtPassword.Text, _
                                           txtDatabase.Text)
    
            form2.Show()
        End Sub
    
        ...
    
    End Class
    

    the Second-Form code:

    Public Class Form2
    
        ...
    
        Public cnString As String
        Public Sub New(datasourcePrm As String, _
                       usernamePrm As String, _
                       passwordPrm As String, _
                       databasePrm As String)
            cnString = "datasource=" & datasourcePrm & ";" _
                     & "username=" & usernamePrm & ";" _
                     & "password=" & passwordPrm & ";" _
                     & "database=" & databasePrm & ";"
    
            InitializeComponent()
        End Sub
    
        ...
    
    End Class
    
  2. Const reresent an absolute value, known at compile time. its impossible assign a "dynamic" value, so:

    Public a As String
    Public Const b As String = a       'error: a its a variable
    Public Const b As String = "abc"   'correct
    

Hope I understood and helped.