Miggs Miggs - 5 months ago 26
Vb.net Question

Call a method from another form vb.net

I have been doing this application for a while and now I want to call a method from by main form and include it into another form to make it run what I want. In my main form this is the method that I have:

Public Sub MostrarResultadoTotal()
SQLCon = New SqlConnection
SQLCon.ConnectionString = "......"
Try
SQLCon.Open()
Query = "SELECT
CAST(SUM(CAST(Filesize as float)) / 1024 / 1024 AS DECIMAL(10,2))
FROM infofile"
SqlCmd = New SqlCommand(Query, SQLCon)
SqlDR = SqlCmd.ExecuteReader
If SqlDR.Read() Then
If SqlDR.IsDBNull(0) Then
lblResultadoTotal.Text = "0,00"
Else
lblResultadoTotal.Text = SqlDR.GetDecimal(0)
End If
End If
SQLCon.Close()
Catch ex As SqlException
MsgBox(ex.Message)
Finally
SQLCon.Dispose()
End Try
End Sub


And I want to call this on a delete button. Do you have any idea how can I solve my problem?

This is the method:

'Mudar a cor das labels dependendos to tamanho total
Sub ChangeLabelColor()
If lblResultadoTotal.Text <= 3.9 Then
lblResultadoTotal.ForeColor = Color.Green
lblGB.ForeColor = Color.Green
ElseIf (lblResultadoTotal.Text >= 4) And (lblResultadoTotal.Text <= 6.9) Then
lblResultadoTotal.ForeColor = Color.Orange
lblGB.ForeColor = Color.Orange
ElseIf lblResultadoTotal.Text >= 7 Then
lblResultadoTotal.ForeColor = Color.Red
lblGB.ForeColor = Color.Red
End If

Answer

In that case, your method contains data access logic, which should be separated from your UI layer logic (Forms). It should be in a separate class, which is then called by both forms.

Friend Class DataAccess
    Public Function MostrarResultadoTotal() As String
        SQLCon = New SqlConnection
        SQLCon.ConnectionString = "......"
        Try
            SQLCon.Open()
            Query = "SELECT 
                    CAST(SUM(CAST(Filesize as float)) / 1024 / 1024 AS DECIMAL(10,2))
                    FROM infofile"
            SqlCmd = New SqlCommand(Query, SQLCon)
            SqlDR = SqlCmd.ExecuteReader
            If SqlDR.Read() Then
                If SqlDR.IsDBNull(0) Then
                    Return "0,00"
                Else
                    Return SqlDR.GetDecimal(0)
                End If
            End If

        Catch ex As SqlException
            MsgBox(ex.Message)
        Finally
            ' Always close connection 
            SQLCon.Close()
            SQLCon.Dispose()
        End Try
    End Function
End Class

Then, from you forms, just declare an instance of your date access logic:

Dim dataAccess = New DataAccess();

And call it:

lblResultadoTotal.Text = dataAccess.MostrarResultadoTotal()