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

时间:2015-03-14 15:06:16

标签: vb.net scope

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

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

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

我该怎么做呢?我是否需要以某种方式使此利润变量成为公共共享变量才能以其他形式访问它?是否有另一种方法可以增加此值并显示新增加的变量?

1 个答案:

答案 0 :(得分:1)

共享变量如何帮助你?

你应该拆分适用于数据的函数,以及与表单一起使用的函数。换句话说,当您需要显示数据时,请致电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

这不完全是生产代码,仅用于示例