我需要一个 Public 共享变量吗?

Will I Need a Public Shared Variable Here?

我在我的程序的一种形式中有这个子程序来计算和显示我的数据库的总利润:

Public Sub Profit()
    Try
        Using connection As New OleDbConnection(connectionstring)
            connection.Open()

            Dim Command As New OleDbCommand("SELECT SUM(Price) FROM ItemsSold", connection)
            Dim command2 As New OleDbCommand("SELECT SUM(TotalCost) FROM Inventory", connection)
            Dim Turnover As Double = Convert.ToDouble(Command.ExecuteScalar())
            Dim Cost As Double = Convert.ToDouble(command2.ExecuteScalar())
            Dim TotalProfit As Double = Turnover - Cost

            lblProfit.Text = "Profit: £" & TotalProfit
            lblProfit2.Text = "Profit: £" & TotalProfit
            lblProfit3.Text = "Profit: £" & TotalProfit
            lblProfit4.Text = "Profit: £" & TotalProfit

            connection.Close()
        End Using
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

此外,在另一种形式的程序中,我正在使用用户提供的值更新数据库 table。我想要做的是将此输入值添加到 Profit() 子标签中显示的利润中。

我该怎么做?我是否需要以某种方式使这个利润变量成为 public 共享变量,以便能够以我的其他形式访问它?有没有另一种方法来增加这个值并显示新增加的变量?

共享变量应该如何帮助您?

您应该拆分处理数据的函数和处理表单的函数。换句话说,当你需要显示数据时,你调用GetProfit,当你需要更新利润时,你调用SetProfit(ByVal profit As Double)。然后在您的项目中使用它们。

根据你的代码,我想它看起来应该是这样的

Public Sub GetProfit()
    Dim profit As Double
    Try
        Using connection As New OleDbConnection(connectionstring)
            connection.Open()

            Dim Command As New OleDbCommand("SELECT SUM(Price) FROM ItemsSold", connection)
            Dim command2 As New OleDbCommand("SELECT SUM(TotalCost) FROM Inventory", connection)
            Dim Turnover As Double = Convert.ToDouble(Command.ExecuteScalar())
            Dim Cost As Double = Convert.ToDouble(command2.ExecuteScalar())
            Dim TotalProfit As Double = Turnover - Cost

            profit = TotalProfit 

            connection.Close()
        End Using
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

    ' Return the result
    return profit
End Sub

并进行更新

Public Sub SetProfit(ByVal newProfit As Double)
    Try
        Using connection As New OleDbConnection(connectionstring)
            connection.Open()

            ' Commands for updating data (just for example)
            Dim Command As New OleDbCommand("UPDATE ItemsSold SET Price = " & newProfit)

            connection.Close()
        End Using
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

然后当你处理你的表单时,你就是这样做的

Private Sub Form1_Load()
   Label1.Text = GetProfit()
   Label2.Text = GetProfit()
End Sub

何时需要更新

Private Sub Button1_Click()
  SetProfile(GetProfit() + 5)
End

不完全是生产代码,只是为了举例