SqlDataReader收集一行值而不是所有行?困惑& SqlDataReaders的新手

时间:2018-04-03 17:47:17

标签: asp.net if-statement sqldatareader

两张桌子:

CART (CartID,UserID,DateCreated,ProductID,ProductName,尺寸,价格,数量,小计,小时工作)

产品(产品ID,名称,标注,价格,尺寸,图片,缩略图,重量,LDescription,库存,CategoryID,小时工作)

我正在尝试做什么: 根据SELECT语句选择的categoryID的全部显示两个按钮之一。

类别ID范围为1-7。如果选择的任何CategoryID与“1”“2”或“7”匹配,则应显示“创建预订”按钮,否则应显示“交付选项”按钮。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

       'Display the correct button:
    Dim conn As SqlConnection = New SqlConnection(ConnectionString)
    Dim cmd As SqlCommand = New SqlCommand
    cmd.CommandText = "SELECT products.CategoryID FROM Products INNER JOIN Cart on products.ProductID = cart.ProductID WHERE ([UserID] = @UserID) AND ([DateCreated] = CONVERT(date, GETDATE()))"

    Dim UserID As SqlParameter = New SqlParameter("@UserID", SqlDbType.NVarChar, 128)
    UserID.Value = "249f38b8-e745-44f4-8d78-806b0e5e7e0e"
    cmd.Parameters.Add(UserID)

    cmd.Connection = conn
    conn.Open()
    cmd.ExecuteNonQuery()

    Dim reader As SqlDataReader = cmd.ExecuteReader
    Dim CategoryID As Integer

    While reader.Read()
         'CategoryID = reader.GetValue(0)
    CategoryID = CType(reader("CategoryID"), Integer)
    End While
    conn.Close()

    lblTest.Text = CategoryID

    If CategoryID = "1" Or "2" Or "7" Then
            btnCreateBooking.Visible = True
        Else
            btnDeliveryOptions.Visible = True
        End If
End Sub

但是,购物车中 last 产品的CategoryID由SqlDataReader生成到标签/变量中,而“创建预订”按钮仅

1 个答案:

答案 0 :(得分:0)

在这里找到答案:https://forums.asp.net/t/1401666.aspx?C+datareader+returning+multiple+rows+and+asp+Label+question+

If reader.HasRows Then
        While reader.Read()
            lblTest.Text = (lblTest.Text _
                + (reader("CategoryID").ToString + "<br>"))
        End While
        conn.Close()
    End If 

并将我的if语句更正为:

If lblTest.Text.Contains("1") Or lblTest.Text.Contains("2") Or lblTest.Text.Contains("7") Then
        btnCreateBooking.Visible = True
    Else
        btnDeliveryOptions.Visible = True
        End If