大家来看ASP.net中两种方法实现简单的购物车

 

这是一个购物页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        Label1.Text = "欢迎使用CSDN购物平台";
            TableRow row = new TableRow();
            TableCell cell = new TableCell();

            TableCell h1 = new TableCell();
            h1.Text = "品名";
          
            row.Cells.Add(h1);

            TableCell h2 = new TableCell();
            h2.Text = "价格";
            row.Cells.Add(h2);

            TableCell h3 = new TableCell();
            h3.Text = "日期";
            row.Cells.Add(h3);

            TableCell h4 = new TableCell();
            h4.Text = "购买数量";
            row.Cells.Add(h4);
            Table1.Rows.Add(row);
            string sqlcon = ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
            using (SqlConnection con = new SqlConnection(sqlcon))
            {
                using (SqlCommand cmd = new SqlCommand("select * from product", con))
                {
                    SqlDataReader myreader;
                    con.Open();
                    myreader = cmd.ExecuteReader();
                    int i = 0;
                    while (myreader.Read())
                    {
                        TableRow row1 = new TableRow();
                        TableCell name = new TableCell();
                        name.ID = i.ToString() + "1";
                        name.Text = myreader["品名"].ToString();
                        row1.Cells.Add(name);

                        TableCell pirce = new TableCell();
                        pirce.ID = i.ToString() + "2";
                        pirce.Text = myreader["价格"].ToString();
                        row1.Cells.Add(pirce);

                        TableCell datetime = new TableCell();
                        datetime.ID = i.ToString() + "3";
                        datetime.Text = myreader["生产日期"].ToString();
                        row1.Cells.Add(datetime);

                        TableCell num = new TableCell();
                        
                       
                            DropDownList ddl = new DropDownList();
                            ddl.AutoPostBack = true;
                            ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
                            for (int i1 = 0; i1 < 100; i1++)
                            {
                                 ListItem ls = new ListItem(i1.ToString(), i1.ToString());
                                ddl.Items.Add(i1.ToString());
                            }
                            num.Controls.Add(ddl);
                            row1.Cells.Add(num);
                      
                        TableCell btn = new TableCell();
                        btn.ID = i.ToString() + "4";
                        Button button = new Button();
                        button.CommandName = myreader["品名"].ToString();
                        button.CommandArgument = myreader["品名"].ToString() + "," + myreader["价格"].ToString() + "," + HiddenField1.Value;//+";";
                        button.Text = "添加";
                        button.Command += new CommandEventHandler(button_Command);
                        btn.Controls.Add(button);
                        row1.Cells.Add(btn);

                        Table1.Rows.Add(row1);
                        i++;
                    }
                }
            }
            Table1.Width = 500;
            Table1.BorderStyle = BorderStyle.Dotted;
            Table1.BorderColor = System.Drawing.Color.Blue;
            Table1.DataBind(); 
 
 
     }

    void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
       DropDownList ddl= sender as DropDownList;
       HiddenField1.Value = ddl.SelectedItem.Text;
    }

    void button_Command(object sender, CommandEventArgs e)
    {
        NewMethod(e.CommandName.ToString(),e.CommandArgument.ToString());


    }

    private void NewMethod(string outname,string outmessage)
    {
        string name =outname ;                   //行名
        int namelength = name.Length;             //行长
        string msg = Session["msg"].ToString();   //信息
        int msglength = msg.Length;               //信息长度
        string[] record = null;                   //单记录 数据
        string[] str = msg.Split(';');             //第条记录
        string newrecord = "";                    //修改后的记录
        bool b = false;                           //作一个标记

        foreach (var item in str)
        {
            record = item.Split(',');             //每条记录数据

                if (record[0] == name)
                {
                    record[2] = (Convert.ToInt32(record[2]) + Convert.ToInt32(HiddenField1.Value)).ToString();
                    b = true;                          //找到了

                }

                newrecord += ";" + record[0] + "," + record[1] + "," + record[2];   //这里是重新加载 下数据  

        }
        if (b)                                       //找到后要执行的
        {
            if (Session["msg"].ToString() != null)
            {
                string str1 = newrecord.Substring(1);
                Session["msg"] = str1;
            }
            else
            {
                Session["msg"] = newrecord;
            }
        }
        else                                           //没有找到要执行的
        {
           // Session["msg"] += ";" +name + ",50,10";    //添加一条新记录
           Session["msg"] += ";" +outmessage;
        }
     
       // Response.Write(Session["msg"].ToString() + "</br>");
        Label1.Text = "添加成功!";
    }


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

这是您购物车的页面:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = createtable();
         string msg=Session["msg"].ToString();
      
         foreach (var item in str)
        {
            string[] tempstr = item.Split(',');
            DataRow row = dt.NewRow();
            row[0] = tempstr[0];     //显示购买物品我名字
            row[1] = tempstr[1];    //显示购买物品的价格
            row[2] = tempstr[2];   //显示购买物品的数量
            row[3] = "2011-1-1";
            row[4] = Convert.ToInt32(row[2]) * Convert.ToDouble(row[1]);   //进行总金额的计算
            dt.Rows.Add(row);
        }
        GridView1.DataSource = dt;
        GridView1.DataBind(); 


    }

    private static DataTable createtable()
    {
        DataTable dt = new DataTable("Shopping");

        DataColumn col1 = new DataColumn("产品名称", Type.GetType("System.String"));
        dt.Columns.Add(col1);
       // dt.PrimaryKey = new DataColumn[] { col1 };

        DataColumn col2 = new DataColumn("产品单价", Type.GetType("System.Double"));
        dt.Columns.Add(col2);

        DataColumn col4 = new DataColumn("购买数量", Type.GetType("System.Int32"));
        dt.Columns.Add(col4);

        DataColumn col3 = new DataColumn("生产日期", Type.GetType("System.String"));
        dt.Columns.Add(col3);


        DataColumn col5 = new DataColumn("消费金额", Type.GetType("System.Double"));
        dt.Columns.Add(col5);


        return dt;
    }
}

 

Global.asax的代码:

<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // 在应用程序启动时运行的代码

    }
   
    void Application_End(object sender, EventArgs e)
    {
        //  在应用程序关闭时运行的代码

    }
       
    void Application_Error(object sender, EventArgs e)
    {
        // 在出现未处理的错误时运行的代码

    }

    void Session_Start(object sender, EventArgs e)
    {
        // 在新会话启动时运行的代码
        Session["msg"]="大米,10,1";                 //先写入Session中一条记录
    }

    void Session_End(object sender, EventArgs e)
    {
        // 在会话结束时运行的代码。
        // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 InProc 时,才会引发 Session_End 事件。
        // 如果会话模式设置为 StateServer
        // 或 SQLServer,则不会引发该事件。

    }
      
</script>


 

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭