将数据从数据库放到label.text

时间:2015-10-07 09:24:40

标签: vb.net winforms

当我调用setText方法时,它不会返回任何内容。

setText("Sprite", "lblSpriteQty.Text", "lblSpriteTP.Text", 15)

我用于方法setText的代码

 Public Sub setText(ByVal productname As String, ByVal qty As String, ByVal tp As String, ByVal price As Integer)

    Using cs As New SqlConnection("Data Source=KARL-PC;Initial Catalog=ShawarmaToldb;Integrated Security=True")
        Using cmd As New SqlCommand("SELECT SUM(quantity) FROM [tblOrderDetails] WHERE productid = (SELECT productid FROM [tblProduct] WHERE productname = @productname)", cs)
            cmd.Parameters.AddWithValue("@productname", productname)
            cmd.CommandType = CommandType.Text
            cs.Open()
            cmd.ExecuteNonQuery()
            Dim dr As SqlDataReader = cmd.ExecuteReader()
            While dr.Read()
                If IsDBNull(dr.GetValue(0)) Then
                    qty = "0" 'but if i put lblSpriteQty.Text instead of qty it's working
                    tp = "0" 'same as here
                Else
                    qty = dr.GetValue(0).ToString
                    tp = dr.GetValue(0).ToString * price
                End If
            End While
        End Using
    End Using
End Sub

1 个答案:

答案 0 :(得分:1)

您正在修改局部变量(方法参数),而不是将qtytp返回到调用方法。但即使你制作它们ByRef,你也无法改变它们,因为字符串是不可变的。而是在此方法中设置文字,或者将其设为Function,为所需数量返回Integer

Public Function GetSumQuantity(ByVal productname As String) As Integer
    Using cs As New SqlConnection("Data Source=KARL-PC;Initial Catalog=ShawarmaToldb;Integrated Security=True")
        Using cmd As New SqlCommand("SELECT SUM(quantity) FROM [tblOrderDetails] WHERE productid = (SELECT productid FROM [tblProduct] WHERE productname = @productname)", cs)
            cmd.Parameters.AddWithValue("@productname", productname)
            cs.Open()
            Dim sumQuantityObj = cmd.ExecuteScalar()
            If DbNull.Value = sumQuantityObj Then Return 0
            Return DirectCast(sumQuantityObj, Integer)
        End Using
    End Using
End Sub

现在您可以计算该值并将其分配给调用方法中的标签文本:

Dim sumQuantity As Integer = GetSumQuantity("IPhone")
Dim tp = price * sumQuantity 
lblSpriteQty.Text = tp.ToString()
相关问题