2012-05-05 5 views
0

동일한 책 제목을 장바구니에 삽입 할 때 데이터 테이블을 업데이트하려고했습니다. 양의데이터 테이블의 값을 업데이트하십시오.

public bool checkBook(DataTable dt, String title) 
{ 
    bool returnval = false; 
    try 
    { 

     foreach (DataRow dr in dt.Rows) 
     { 
      String checktitle = dr["Title"].ToString(); 
      if (title == checktitle) 
      { 
       int a = Convert.ToInt32(dr["quantity"].ToString()); 
       dr["quantity"] = a + 1; 
       returnval = true; 
      } 

     } 
    } 
    catch (Exception ex) 
    { 
     //do something 
    } 
    return returnval; 
} 

초기 값은 1입니다,하지만 버튼이 제출되었을 때, 수량은 여전히 ​​1이지만, 세 번째 시간을 입력 할 때 숫자가 하나 증가하기 시작했다. 나는 실수가 어디인지 이해하지 못한다.

편집 :

protected void ListView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    String title = ((Label)(ListView1.Items[ListView1.SelectedIndex].FindControl("Title"))).Text; ; 
    decimal price = decimal.Parse(((Label)(ListView1.Items[ListView1.SelectedIndex].FindControl("Price"))).Text); 

    cart cart = new cart(title, price); 

    if (HttpContext.Current.Session["Cart"] != null) 
    { 
     DataTable shoppingcart = (DataTable)HttpContext.Current.Session["Cart"]; 
     bool check = checkBook(shoppingcart, title); 
     if (check != true) 
     { 
      ShoppingCart.DataSource = cart.cartrow(shoppingcart); 
      ShoppingCart.DataBind(); 
     } 
     else 
     { 
      // if is true, it suppose to increase the quantity here 

      } 

     } 
    } 

    else 
    { 

     HttpContext.Current.Session["Cart"] = cart.shoppingCart(); 
     ShoppingCart.DataSource = cart.shoppingCart(); 
     ShoppingCart.DataBind(); 
    } 

} 

클래스 ::

당신은 문제가 무엇인지 결정하기 위해 코드의 더 많은 것을 보여줄 필요가
String title { get; set; } 
decimal price { get; set; } 
int quantity = 1; 
DataTable CartTable; 
DataRow tableRow; 
public cart(String _title, decimal _price) 
{ 
title = _title; 
price = _price; 
} 
public DataTable shoppingCart() 
{ 
CartTable = new DataTable("cart"); 

CartTable.Columns.Add("ID", typeof(Int32)); 
CartTable.Columns["ID"].AutoIncrement = true; 
CartTable.Columns["ID"].AutoIncrementSeed = 1; 

CartTable.Columns.Add("Title"); 
CartTable.Columns.Add("Price"); 
CartTable.Columns.Add("quantity"); 
CartTable.Columns["quantity"].DataType = typeof(Int32); 

tableRow = CartTable.NewRow(); 
tableRow["Title"] = title; 
tableRow["Price"] = price; 
tableRow["quantity"] = quantity; 
CartTable.Rows.Add(tableRow); 
return CartTable; 
} 

public DataTable cartrow(DataTable _cart) 
{ 

tableRow = _cart.NewRow(); 
tableRow["Title"] = title; 
tableRow["Price"] = price; 
tableRow["quantity"] = quantity; 
_cart.Rows.Add(tableRow); 
return _cart; 

} 
+0

질문이 명확하지 않습니다. 더 자세히 설명해주십시오. '버튼'은 어디에 있습니까? 버튼을 제출하면 무엇을 의미합니까? – jams

+0

질문이 명확하지 않습니다. 데이터 테이블의 스키마를 제공하십시오. html 마크 업으로 전체 코드를 제공하십시오. –

+0

동일한 책 추가 - 장바구니를 누를 때 문제가 발견되었습니다. 처음에는 추가하지 않았지만 같은 URL을 가져 와서 다른 탭에서 열 때 하나에서 두 개까지 추가됩니까? 내 코딩에 문제가 있습니까? – eugene

답변

1

. 데이터 테이블에 바인딩하고 있습니까? 버튼을 클릭 한 후 다시 만드시겠습니까?

어쨌든, 다음은 예상대로 작동하는 것을 보여주는 약간의 코드입니다. System.Data.DataSetExtensions의 제네릭 필드 확장 메서드를 사용합니다.

HttpContext.Current.Session["Cart"] = cart.shoppingCart(); 
ShoppingCart.DataSource = cart.shoppingCart(); 

이유는 다음과 같습니다

namespace StackOverflowTestCode 
{ 
    using System.Data; 
    using Microsoft.VisualStudio.TestTools.UnitTesting; 

    [TestClass] 
    public class RandomTests 
    { 
     [TestMethod] 
     public void DataTableUpdate_Test() 
     { 
      DataTable dataTable = new DataTable(); 
      dataTable.Columns.Add("Title", typeof(string)); 
      dataTable.Columns.Add("Quantity", typeof(int)); 

      dataTable.Rows.Add("TitleOne", 0); 
      dataTable.Rows.Add("TitleTwo", 0); 
      dataTable.Rows.Add("TitleThree", 0); 

      DataRow[] rowsToUpdate = 
       dataTable.Select("Title = 'TitleTwo'"); 

      if(rowsToUpdate != null && rowsToUpdate.Length == 1) 
      { 
       rowsToUpdate[ 0 ][ "Quantity" ] = 
        rowsToUpdate[ 0 ].Field<int>("Quantity") + 1; 
      } 

      // The right row was updated. 
      Assert.AreEqual(1, dataTable.Rows[ 1 ][ "Quantity" ]); 

      // The other rows were not updated. 
      Assert.AreEqual(0, dataTable.Rows[ 0 ][ "Quantity" ]); 
      Assert.AreEqual(0, dataTable.Rows[ 2 ][ "Quantity" ]); 
     } 
    } 
} 

즉시 홀수 및 버그의 가능한 소스로 나를 밖으로 점프 유일한 것은 다음과 같은 당신의 갱신 후

편집 그 방법을 두 번 부르는거야?

+0

첫 번째는 세션에 데이터 테이블을 바인딩하는 것이고, 다른 하나는리스트 뷰에 있습니다. 그렇게 할 수있는 더 좋은 방법이 있습니까? – eugene

+0

@eugene 같은 것을 나타 내기 위해 두 개의 변수를 만들면됩니다. 한 번 메서드를 호출하고 변수를 설정 한 다음 세션과 데이터 원본을 해당 변수로 설정하는 것이 좋습니다. 메서드를 두 번 연속 호출하는 것은 거의 확실합니다. –

+0

정보를 제공해 주셔서 감사 드리며, 저는 아직 프로그래밍에 새로운 사람입니다. – eugene

관련 문제