購物車的實現

--數據庫訪問類

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;


/// <summary>
/// ConBase 的摘要說明
/// </summary>
public class ConBase
{
    public SqlConnection objSqlConnection = null;
    public SqlCommand objSqlCommand = null;
    public SqlDataAdapter objSqlDataAdapter = null;
    public SqlDataReader objSqlDataReader = null;
    public DataSet objDataSet = null;
       
 public ConBase()
 {
  //
  // TODO: 在此處添加構造函數邏輯
  //       
       
 }

    public void getCon()
    {
        string strConn = ConfigurationManager.AppSettings["StrCon"].ToString();
        objSqlConnection = new SqlConnection(strConn);
        objSqlDataAdapter = new SqlDataAdapter();
        objSqlConnection.Open();
    }

    /// <summary>
    /// 查詢結果
    /// </summary>
    /// <param name="sql">sql語句</param>
    /// <param name="type">1和2</param>
    /// <param name="tableName">表名</param>
    /// <returns>如果是type== 1,返回dataset  2就返回 </returns>
    public object searchData(string sql, int type, string tableName)
    {
        if (objSqlConnection == null)
        {
            getCon();
        }
        try
        {
            objSqlDataAdapter.SelectCommand = new SqlCommand(sql, objSqlConnection);

            if (type == 1)
            {
                objDataSet = new DataSet();
                objSqlDataAdapter.Fill(objDataSet, tableName);
                return objDataSet;
            }
            else if (type == 2)
            {
                objSqlDataReader = objSqlDataAdapter.SelectCommand.ExecuteReader();
                return objSqlDataReader;
            }
        }
        catch (Exception ce)
        {
            dispose();
            throw ce;
        }
        return null;
    }

    //增加,修改,刪除數據的方法
    public void updateData(string sql)
    {
        if (objSqlConnection == null)
        {
            getCon();
        }
        try
        {
            objSqlCommand = new SqlCommand(sql, objSqlConnection);
            objSqlCommand.ExecuteNonQuery();
        }
        catch (Exception ce)
        {
            dispose();
            throw ce;
        }
    }

    //消毀的方法 
    public void dispose()
    {
        if (objSqlConnection != null)
        {
            if (objSqlConnection.State == ConnectionState.Open)
            {
                if (objSqlDataReader != null)
                {
                    objSqlDataReader.Close();
                }
                objSqlConnection.Close();
            }
        }
        GC.SuppressFinalize(true);
    }
}

 

 

 

---------------------------------------------------起啓頁類

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    comm objcomm = new comm();
    DataSet objDataSet = null;
    public static DataTable table = null;
    protected void Page_Load(object sender, EventArgs e)
    {       
        if (!Page.IsPostBack)
        {
            if (Session["CartTable"] == null)
            {
                createCart();
            }           
            this.objDataSet = objcomm.getGoodsInfo();
            BindData();          
        }
    }

    //綁定數據的方法
    public void BindData()
    {
        this.dg.DataSource = objDataSet;
        this.dg.DataBind();
    }

    //創建購物車
    public void createCart()
    {
        objDataSet = new DataSet();
        table = new DataTable("CartTable");
        this.objDataSet.Tables.Add(table);
        DataColumn newColumn ;
        newColumn = new DataColumn("GoodId", System.Type.GetType("System.Int32"));
        table.Columns.Add(newColumn);

        newColumn = new DataColumn("GoodsName", System.Type.GetType("System.String"));
        table.Columns.Add(newColumn);

         newColumn = new DataColumn("GoodsPrice", System.Type.GetType("System.Decimal"));
        table.Columns.Add(newColumn);

        newColumn = new DataColumn("GoodsQuantity", System.Type.GetType("System.Int32"));
        table.Columns.Add(newColumn);       
    }

    //放入購物車的按鈕事件
    protected void BtnSelect_Click(object sender, EventArgs e)
    {
       
    }
    protected void dg_SelectedIndexChanged(object sender, EventArgs e)
    {
        int GoodId = int.Parse(dg.SelectedItem.Cells[0].Text);
        string GoodsName = dg.SelectedItem.Cells[1].Text;
        decimal GoodsPrice = decimal.Parse(dg.SelectedItem.Cells[2].Text);

        int GoodsQuantity = int.Parse(dg.SelectedItem.Cells[3].Text);

    //    int GoodsQuantity = int.Parse(table.Rows[dg.SelectedIndex][3].ToString());
      //  Response.Write(dg.SelectedItem.Cells[1].Text.ToString());
     
        bool isFlag = true;
        for (int i = 0; i < table.Rows.Count; i++)
        {
            //如果有些商品  ++ 數量     
           
            if (table.Rows[i][0].ToString().Equals(GoodId.ToString()))
            {
                foreach (DataRow rows in table.Rows)
                {
                    if (rows[0].Equals(dg.SelectedItem.Cells[0].Text))
                    {
                        GoodsQuantity = int.Parse(rows[3].ToString());
                        //Response.Write(" 中  " + GoodsQuantity);
                        break;
                    }
                }

                table.Rows[i][3] = GoodsQuantity + int.Parse(dg.SelectedItem.Cells[3].Text);
                isFlag = false;
            }
        }
       
        if (isFlag)
        {
            // 添加新行         
                DataRow newDR = table.NewRow();
                newDR["GoodId"] = GoodId;
                newDR["GoodsName"] = GoodsName;
                newDR["GoodsPrice"] = GoodsPrice;
                newDR["GoodsQuantity"] = GoodsQuantity;
                table.Rows.Add(newDR);
        }
               // 保存到Session中
        table.AcceptChanges();     
        Session["CartTable"] = table;      
    }
    protected void btnLook_Click(object sender, EventArgs e)
    {
        Response.Redirect("ShoopingCart.aspx");
    }
}

 

 

---------------------------------------------------

購物管理類using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class ShoopingCart : System.Web.UI.Page
{
    DataTable table = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        table = (DataTable)Session["CartTable"];
        if (!Page.IsPostBack)
        {
            if (table != null)
            {
              BindData();
            }
        } 
    }

    // 綁定數據的方法
    public void BindData()
    {
        this.dgc.DataSource = table.DefaultView;
        this.dgc.DataBind();
    }

    protected void BtnContinue_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }

    //刪除的事件
    protected void dgc_DeleteCommand(object source, DataGridCommandEventArgs e)
    {
        DataRow[] rows = table.Select("GoodId= "+int.Parse(table.Rows[e.Item.ItemIndex][0].ToString()));
        DataRow row = rows[0];
        table.Rows.Remove(row);
        table.AcceptChanges();
        //刪除後已經沒有數據了
        this.dgc.CurrentPageIndex = 0;
        BindData();
    }

    //編輯按鈕的事件 
    protected void dgc_EditCommand(object source, DataGridCommandEventArgs e)
    {
        this.dgc.EditItemIndex = e.Item.ItemIndex;
        BindData();
    }
    protected void dgc_CancelCommand(object source, DataGridCommandEventArgs e)
    {
         this.dgc.EditItemIndex = -1;
         BindData(); 
    }
    protected void dgc_UpdateCommand(object source, DataGridCommandEventArgs e)
    {
        int count=int.Parse(((TextBox)e.Item.FindControl("tex")).Text);      
        table.Rows[(dgc.CurrentPageIndex*2)+e.Item.ItemIndex][3] =count;     
        Session["CartTable"] = table;
        this.dgc.EditItemIndex = -1;
        BindData(); 
    }
    protected void dgc_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        this.dgc.CurrentPageIndex = e.NewPageIndex;
        BindData();
    }
     
    protected void dgc_ItemDataBound(object sender,DataGridItemEventArgs e)
    {   

         // 計算出來的總價啊! 
         decimal sum = 0;
         Decimal price = 0 ;
         int num  = 0 ;
         for (int i = 0; i < table.Rows.Count; i++)
         {
             price = Decimal.Parse(table.Rows[i][2].ToString());
             num = int.Parse(table.Rows[i][3].ToString());
             sum += price * num;
         }
         Label1.Text = sum.ToString() + "元";
    }
    protected void dgc_ItemCommand(object source, DataGridCommandEventArgs e)
    {
     
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章