2012-03-20 4 views
0

참고 :이 코드는 제가 지금 읽고있는 튜토리얼 북에서 실제로 코드하므로이 코드가 크게 실망 스럽습니다. VB.NET 4, Visual Studio 2010 및 MS SQL Server R2 2008을 사용하여 기본 장바구니를 만들고 있습니다. 아래 코드는 세션 변수를 읽고 적절한 ProductID를 제거하여 장바구니에서 항목을 제거하기로되어 있습니다. 수정 문자열을 세션 변수로 리턴하십시오. 그런 다음 데이터를 다시 그리기 위해 gridview (gvCart)에 데이터를 다시 바인딩해야합니다 ...하지만 여기에 오류가있는 것 같습니다.장바구니 제거 버튼을 만들려고 시도합니다.

Visual Studio에서 사이트를 빌드 할 때마다 정상적으로 유효성이 검사됩니다. 마지막 괄호으로 나를 가리키는 IDE와

Incorrect syntax near ')'.

:하지만 사이트 운영, 모든 시간은 나에게 오류를 제공 제거 버튼을 사용하려고.

나는 좋은 4 시간 동안 내 머리를 뽑아왔다.

Protected Sub gvCart_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvCart.SelectedIndexChanged 
    'This method is hooked to the Remove button & is removing items from the cart 
    Dim strProductId As String = gvCart.SelectedRow.Cells(1).Text 
    If Session("Cart") IsNot Nothing Then 
     'Remove selected ProductID from Session string and retrieve session string 
     Dim strCart As String = Session("Cart").ToString() 
     Dim arIDs As String() = strCart.Split(",") 

     'Iterate through ID's in the 'Cart' array and rebuild the string leaving out the selected ID 

     strCart = String.Empty 
     For Each str As String In arIDs 
      'use Trim to remove leading and trailing spaces 
      If str.Trim() <> strProductId.Trim() Then 
       strCart += str + ", " 
      End If 
     Next 

     'Remove trailing space and comma 
     If strCart.Length > 1 Then 
      strCart = strCart.Trim() 
      strCart = strCart.Substring(0, strCart.Length - 1) 
     End If 

     'Put back into session var 
     Session("Cart") = strCart 

     'Rebind gvCart, which forces the sqldatasource to requery 
     gvCart.DataBind() 
    End If 
End Sub 

[편집] 나는 또한 완성을 위해 sqlCart_Selecting 이벤트를 실행하는 코드를 포함하고 :

Protected Sub sqlCart_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles sqlCart.Selecting 
    Trace.Warn("sqlCart_Selecting") 'aids debugging 

    Dim strCart As String = String.Empty 
    If Session("Cart") IsNot Nothing Then 
     strCart = Session("Cart").ToString 
     e.Command.CommandText &= " WHERE product.ProductID IN (" + strCart + ") AND culture.CultureID = 'en'" 
    Else 
     e.Cancel = True 
    End If 


End Sub 

또한 gridview에 'gvCart'에서 사용하는 SQL 쿼리를 포함하여 [편집] 내가 여기에 총을 쏘면됩니다

<asp:SqlDataSource ID="sqlCart" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" SelectCommand="SELECT product.ProductID, product.Name, product.ProductNumber, product.Color, subcat.Name AS SubcategoryName, cat.Name AS CategoryName, description.Description FROM Production.Product product JOIN Production.ProductSubcategory subcat ON product.ProductSubcategoryID = subcat.ProductSubcategoryID JOIN Production.ProductCategory cat ON subcat.ProductCategoryID = cat.ProductCategoryID JOIN Production.ProductModel model on product.ProductModelID = model.ProductModelID JOIN Production.ProductModelProductDescriptionCulture culture ON model.ProductModelID = culture.ProductModelID JOIN Production.ProductDescription description ON culture.ProductDescriptionID = description.ProductDescriptionID"></asp:SqlDataSource> 


Protected Sub btnAddToCart_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddToCart.Click 
    'The contents of the cart will be saved in a Session object as a string of coma-delimited values of ProductID's 
    Dim strCart As String = String.Empty 
    Dim strProductID As String = gvProducts.SelectedDataKey.Value.ToString() 

    If Session("Cart") Is Nothing Then 
     strCart = strProductID 
    Else 
     strCart = Session("Cart").ToString() + ", " + strProductID 
    End If 

    Session("Cart") = strCart 
    lblCart.Text = strCart 
End Sub 

답변

3

다른 페이지에있는 카트의 내용을 표시하기위한 코드는 우리에게 그리고 모든 것이 표시되지 않기 때문에 ng (예를 들어 SQL 쿼리).

하지만 SQL 쿼리가 IN 절을 사용하고있는 것으로 느껴집니다. 카트가 비었을 때 실패하는 것 같습니다. Session("Cart") 이후

제품 ID의 쉼표로 구분 된 값이 들어, 다음과 같은 SQL 쿼리를 만들 것 빈리스트가 실패 : 메시지와 함께

select id, name 
from products 
where id in() 

:

Incorrect syntax near ')'.

당신은 우리에게 보여해야 Session("Cart")에서 쿼리를 다시로드하는 코드 부분 쿼리를 다시 어셈블해야합니다.

하지만 유용한 트릭이 하나 있습니다. 이것에

strCart = String.Empty 

:

strCart = '-1, ' 

업데이트 난 정말이에 낚시하는 방법을 가르 칠 것입니다

제품 id의 숫자와 0보다 항상 큰 경우이 줄을 변경 하나. 문제를 :)은 여기에 있습니다 :

Dim strCart As String = String.Empty 
If Session("Cart") IsNot Nothing Then 
    strCart = Session("Cart").ToString 
    e.Command.CommandText &= " WHERE product.ProductID IN (" + strCart + ") AND culture.CultureID = 'en'" 
Else 
    e.Cancel = True 
End If 

카트가 비어, Session("Cart")Nothing 아니라 빈 문자열 (당신이 -1 해결 방법을 제거한다)이다.Session("Cart")이 빈 문자열 인 경우 where 절은 " WHERE culture.CultureID = 'en'"이어야하며 제품 ID에는 언급되지 않습니다. 하나님 속도!

+1

와우. 잘 했어 :) – Ryan

+0

카트 페이지를 담당하는 고마워. 제품 선택 페이지에는 카트의 현재 내용을 보여주는 레이블이 있습니다. '장바구니'페이지를 방문한 경우 라벨에 내용의 일부로 '-1'이 표시됩니다. 그것을 보여줄 수있는 방법이 있습니까? –

+0

그건 제가 제안한 대안의 부작용입니다. 해결 방법은 결코 최상의 솔루션이 아닙니다. 실제 솔루션은 세션 ("장바구니")의 목록이 비어있을 때 SQL 쿼리를 올바르게 다시 조합합니다. –

관련 문제