电子商务平台

数据表:

管理员信息表、商品信息表、商品类型表(编号、名称、图片)、订单详细表、图片信息表、用户留言表、会员信息表、商品订单表、回复留言表。

公共类设计:web。config

<configuration>
  <appSettings>
    <add key="ConnectionString" value="server=localhost;database=db_NetStore;UId=sa;password='123'"/>
  </appSettings>
 <system.web>

5个公共类

CommonClass公共方法类

DBClass数据库各种操作

GoodsClass管理对商品信息的各种操作

OrderClass管理对购物订单信息的各种操作

UserClass:管理对用户信息的各种操作

这里只简单介绍CommonClass、DBClass

/// <summary>
    /// 说明:MessageBox用来在客户端弹出对话框,关闭对话框返回指定页。
    /// 参数:TxtMessage 对话框中显示的内容。
    /// Url 对话框关闭后,跳转的页
    /// </summary>
    public string MessageBox(string TxtMessage,string Url)
    {
        string str;
        str = "<script language=javascript>alert('" + TxtMessage + "');location='" + Url + "';</script>";
        return str;
    }

 /// <summary>
    /// 说明:MessageBox用来在客户端弹出对话框。
    /// 参数:TxtMessage 对话框中显示的内容。
    /// </summary>
    public string MessageBox(string TxtMessage)
    {
        string str;
        str = "<script language=javascript>alert('" + TxtMessage + "')</script>";
        return str;
    }

 /// <summary>
    /// 说明:MessageBoxPag用来在客户端弹出对话框,关闭对话框返回原页。
    /// 参数:TxtMessage 对话框中显示的内容。
    /// </summary>
    public string MessageBoxPage(string TxtMessage)
    {
        string str;
        str = "<script language=javascript>alert('" + TxtMessage + "');location='javascript:history.go(-1)';</script>";
        return str;
    }

  /// <summary>
    /// 实现随机验证码
    /// </summary>
    /// <param name="n">显示验证码的个数</param>
    /// <returns>返回生成的随机数</returns>
    public string RandomNum(int n) //
    {
        //定义一个包括数字、大写英文字母和小写英文字母的字符串
        string strchar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        //将strchar字符串转化为数组
        //String.Split 方法返回包含此实例中的子字符串(由指定Char数组的元素分隔)的 String 数组。
        string[] VcArray = strchar.Split(',');
        string VNum = "";
        //记录上次随机数值,尽量避免产生几个一样的随机数          
        int temp = -1;                      
        //采用一个简单的算法以保证生成随机数的不同
        Random rand = new Random();
        for (int i = 1; i < n + 1; i++)
        {
            if (temp != -1)
            {
                //unchecked 关键字用于取消整型算术运算和转换的溢出检查。
                //DateTime.Ticks 属性获取表示此实例的日期和时间的刻度数。
                rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
            }
            //Random.Next 方法返回一个小于所指定最大值的非负随机数。
            int t = rand.Next(61);
            if (temp != -1 && temp == t)
            {
                return RandomNum(n);
            }
            temp = t;
            VNum += VcArray[t];
        }
        return VNum;//返回生成的随机数
    }

 /// <summary>
    /// 用来截取小数点后nleng位
    /// </summary>
    /// <param name="sString">sString原字符串。</param>
    /// <param name="nLeng">nLeng长度。</param>
    /// <returns>处理后的字符串。</returns>
    public string VarStr(string sString, int nLeng)
    {
        int index = sString.IndexOf(".");
        if (index == -1 || index + nLeng >= sString.Length)
            return sString;
        else
            return sString.Substring(0, (index + nLeng + 1));
    }
 
DBClass类  大部分网站都可以用

 

public class DBClass
{
 public DBClass()
 {
  //
  // TODO: 在此处添加构造函数逻辑
  //
 }
    /// <summary>
    /// 连接数据库
    /// </summary>
    /// <returns>返回SqlConnection对象</returns>
    public SqlConnection GetConnection()
    {
        string myStr = ConfigurationManager.AppSettings["ConnectionString"].ToString();
        SqlConnection myConn = new SqlConnection(myStr);
        return myConn;
    }
    /// <summary>
    /// 执行SQL语句,并返回受影响的行数
    /// </summary>
    /// <param name="myCmd">执行SQL语句命令的SqlCommand对象</param>
    public void  ExecNonQuery(SqlCommand myCmd)
    {
        try
        {
            if (myCmd.Connection.State != ConnectionState.Open)
            {
                myCmd.Connection.Open(); //打开与数据库的连接
            }
            //使用SqlCommand对象的ExecuteNonQuery方法执行SQL语句,并返回受影响的行数
            myCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
        finally
        {
            if (myCmd.Connection.State == ConnectionState.Open)
            {
                myCmd.Connection.Close(); //关闭与数据库的连接
            }
        }
    }
    /// <summary>
    /// 执行查询,并返回查询所返回的结果集中第一行的第一列。所有其他的列和行将被忽略。
    /// </summary>
    /// <param name="myCmd"></param>
    /// <returns>执行SQL语句命令的SqlCommand对象</returns>
    public string ExecScalar(SqlCommand myCmd)
    {
        string strSql;
        try
        {
            if (myCmd.Connection.State != ConnectionState.Open)
            {
                myCmd.Connection.Open(); //打开与数据库的连接
            }
            //使用SqlCommand对象的ExecuteScalar方法执行查询,并返回查询所返回的结果集中第一行的第一列。所有其他的列和行将被忽略。

            strSql=Convert.ToString(myCmd.ExecuteScalar());
            return strSql ;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
        finally
        {
            if (myCmd.Connection.State == ConnectionState.Open)
            {
                myCmd.Connection.Close();//关闭与数据库的连接
            }
        }   
    }
    /// <summary>
    /// 说  明:  返回数据集的表的集合
    /// 返回值:  数据源的数据表
    /// 参  数:  myCmd 执行SQL语句命令的SqlCommand对象,TableName 数据表名称
    /// </summary>
    public DataTable GetDataSet(SqlCommand myCmd, string TableName)
    {
        SqlDataAdapter adapt;
        DataSet ds = new DataSet();
        try
        {
            if (myCmd.Connection.State != ConnectionState.Open)
            {
                myCmd.Connection.Open();
            }
            adapt = new SqlDataAdapter(myCmd);
            adapt.Fill(ds,TableName);
            return ds.Tables[TableName];

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);

        }
        finally
        {
            if (myCmd.Connection.State == ConnectionState.Open)
            {
                myCmd.Connection.Close();

            }
        }

    }
    /// <summary>
    /// 执行存储过程语句,返回sqlCommand类对象
    /// </summary>
    /// <param name="strProcName">存储过程名</param>
    /// <returns>返回sqlCommand类对象</returns>
    public SqlCommand GetCommandProc(string strProcName)
    {
        SqlConnection myConn = GetConnection();
        SqlCommand myCmd = new SqlCommand();
        myCmd.Connection = myConn;
        myCmd.CommandText = strProcName;
        myCmd.CommandType = CommandType.StoredProcedure;
        return myCmd;
    }
    /// <summary>
    /// 执行查询语句,返回sqlCommand类对象
    /// </summary>
    /// <param name="strSql">查询语句</param>
    /// <returns>返回sqlCommand类对象</returns>
    public SqlCommand GetCommandStr(string strSql)
    {
        SqlConnection myConn = GetConnection();
        SqlCommand myCmd = new SqlCommand();
        myCmd.Connection = myConn;
        myCmd.CommandText = strSql;
        myCmd.CommandType = CommandType.Text;
        return myCmd;
    }
    /// <summary>
    /// 说  明:  执行SQL语句,返回数据源的数据表
    /// 返回值:  数据源的数据表DataTable
    /// 参  数:  sqlStr执行的SQL语句,TableName 数据表名称
    /// </summary>
    public DataTable GetDataSetStr(string sqlStr, string TableName)
    {
        SqlConnection myConn = GetConnection();
        myConn.Open();
        DataSet ds = new DataSet();
        SqlDataAdapter adapt = new SqlDataAdapter(sqlStr, myConn);
        adapt.Fill(ds, TableName);
        myConn.Close();
        return ds.Tables[TableName];
    }
}

首页技术分析

母板页封装页头页尾左侧导航条用户登录框。而这些部分用了用户控件。

用户与宿主页共享信息,用户控件中可设置为公共成员或get,set访问器的属性

用户控件不能放在app_code 文件夹

如这里的导航控件,用DataList 做导航

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="navigate.ascx.cs" Inherits="userControl_navigate" %>
<table  style="width: 204px; height:448px; font-size: 9pt; font-family: 宋体; vertical-align :top ; background-image: url(../images/index_16.gif);  background-repeat :no-repeat"  border="0" cellpadding="0" cellspacing="0" >
<tr>
<td style="height: 39px">
</td>
</tr>
    <tr align =center style="width: 204px;  font-size: 9pt; font-family: 宋体; vertical-align :top ;">
        <td style="height: 304px">
         <asp:DataList ID="dlClass" runat="server"  OnItemCommand="dlClass_ItemCommand">
                <ItemTemplate>
                    <table >
                        <tr>
                        <td align =left  style ="width :28px; height :25px;vertical-align :bottom">
                        <asp:Image ID="imageIcon" runat="server"  ImageUrl =<%#DataBinder.Eval(Container.DataItem,"CategoryUrl")%> />
                        </td>
                      <td> </td>
                            <td align =left style ="width :80px;  height :25px; font-size: 9pt; font-family: 宋体; vertical-align :bottom " > 
                            <asp:LinkButton ID="lnkbtnClass" runat="server" CommandName="select" CausesValidation="False"  CommandArgument =<%#DataBinder.Eval(Container.DataItem,"ClassID") %>><%# DataBinder.Eval(Container.DataItem, "ClassName") %></asp:LinkButton>
                            </td>
                        </tr>
                       
                    </table>
                </ItemTemplate>
            </asp:DataList>
            </td>
    </tr>
    </table>
    <table  style="width: 204px; height: 181px; font-size: 9pt; font-family: 宋体; vertical-align :top ;  text-align :center; background-image: url(../images/新品上市.jpg); background-repeat :no-repeat"  border="0" cellpadding="0" cellspacing="0">
    <tr>
    <td style="height: 11px; width: 204px;"></td>
    </tr>
     <tr>
        <td  style="width: 204px; height: 169px;">

移动字条
         <marquee direction="up" onmouseout="this.start()" onmouseover="this.stop()" scrollAmount="2" scrollDelay="4" style="width: 130px;height: 128px; font-size: 9pt; font-family: 宋体; vertical-align :top ;  text-align :center; " >本电子商城欢迎您的光临!我们将为您展示各种最新商品,让您的生活更加丰富,购物更加愉快!如果你有什么所需要的,请给本网站留言!</marquee>
        </td>
    </tr>
   
</table>

 

 

public partial class userControl_navigate : System.Web.UI.UserControl
{
    GoodsClass gcObj = new GoodsClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gcObj.DLClassBind(this.dlClass);
            //gcObj.DLNewGoods(this.dlNewGoods);

        }
    }
    protected void dlClass_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "select")
        {
            Response.Redirect("goodsList.aspx?id=" + e.CommandArgument);
        }   
    }
    public string GetClassName(int IntClassID)
    {
       return  gcObj.GetClass(IntClassID);
    }
    protected void dlNewGoods_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "detailSee")
        {
            Session["address"] = "";
            Session["address"] = "Default.aspx";
            Response.Redirect("~/showInfo.aspx?id=" + Convert.ToInt32(e.CommandArgument.ToString()));
        }

    }
}

 

首页实现代码

用3个datalist显示推荐、最新、最热商品

<tr align="left">
        <td align="left" colspan="0" rowspan="0" style="vertical-align: top; width: 574px;
            text-align: left">
                 <asp:HyperLink ID="HyperLink1" runat="server" ImageUrl ="~/images/精品推荐.jpg" NavigateUrl="~/goodsList.aspx?id=2&&var=1" Font-Underline="False" Height="1px" Width="117px"></asp:HyperLink></td>
    </tr>
     
        <tr align="left">
            <td  align="left" style="width :574px;height :3px; vertical-align: top; text-align: left;" colspan="0" rowspan="0" >
               <asp:DataList ID="dLRefine" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" OnItemCommand="dLRefine_ItemCommand" >
                    <ItemTemplate>
                        <table style=" height: 120px">
                            <tr>
                                <td rowspan="5" style="width: 29px">
                                 <asp:Image ID="imageRefine" runat="server"  ImageUrl =<%#DataBinder.Eval(Container.DataItem,"BookUrl")%>/>图片
                                </td>
                                <td colspan="2">
                                <asp:LinkButton ID="lnkbtnRName" runat="server" CommandName="detailSee"  Font-Underline=false  CommandArgument =<%#DataBinder.Eval(Container.DataItem, "BookID")%>>看详情
                                <%#DataBinder.Eval(Container.DataItem, "BookName")%>名称
                                </asp:LinkButton>
                                </td>
                               
                            </tr>
                            <tr>
                                <td>
                                    市场价:</td>
                                <td>
                                 <%#GetVarMKP(DataBinder.Eval(Container.DataItem, "MarketPrice").ToString())%>¥价格
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    热卖价:</td>
                                <td>
                                  <%#GetVarHot(DataBinder.Eval(Container.DataItem, "HotPrice").ToString())%>¥
                                </td>
                            </tr>
                             <tr>
                                <td colspan="2">
                                    <asp:ImageButton ID="imagebtnRefine" runat="server" CommandName="buy" CommandArgument ='<%# DataBinder.Eval(Container.DataItem, "BookID") %>' ImageUrl="~/images/购买.jpg" OnClick="imagebtnRefine_Click" />决定购买
                                    </td>
                            </tr>
                        </table>
                    </ItemTemplate>
                </asp:DataList> 

 

后台

 

public partial class _Default : System.Web.UI.Page
{
    CommonClass ccObj = new CommonClass();
    GoodsClass gcObj = new GoodsClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
             RefineBind();三个绑定
            HotBind();
            DiscountBind();

            ///*判断是否登录*/
            //ST_check_Login();
        }
    }
    public void ST_check_Login()
    {

        if ((Session["UserName"] == null))
        {
            Response.Write("<script>alert('对不起!您不是会员,请先注册!');location='Default.aspx'</script>");
            Response.End();
        }
    }
    //绑定市场价格
    public string GetVarMKP(string strMarketPrice)
    {
        return ccObj.VarStr(strMarketPrice, 2);
    }
    //绑定热卖价格
    public string GetVarHot(string strHotPrice)
    {
        return ccObj.VarStr(strHotPrice, 2);
    }
    protected void RefineBind()
    {
        gcObj.DLDeplayGI(1, this.dLRefine, "Refine");
    }
    protected void HotBind()
    {
        gcObj.DLDeplayGI(3, this.dlHot, "Hot");
    }
    protected void DiscountBind()
    {
        gcObj.DLDeplayGI(2, this.dlDiscount, "Discount");
    }
    public void AddressBack(DataListCommandEventArgs e)
    {
        Session["address"] = "";
        Session["address"] = "Default.aspx";
        Response.Redirect("~/showInfo.aspx?id=" + Convert.ToInt32(e.CommandArgument.ToString()));跳转并传递id参数吗
    }
   

protected void dLRefine_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "detailSee")
        {
            AddressBack(e);
        }
        else if (e.CommandName == "buy")
        {
            AddShopCart(e);
        }

    }
    protected void dlDiscount_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "detailSee")
        {
            AddressBack(e);
        }
        else if (e.CommandName == "buy")
        {
            AddShopCart(e);
        }

    }
    protected void dlHot_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "detailSee")
        {
            AddressBack(e);
        }
        else if (e.CommandName == "buy")
        {
            AddShopCart(e);
        }

    }
    /// <summary>
    /// 向购物车中添加新商品
    /// </summary>
    /// <param name="e">
    /// 获取或设置可选参数,
    /// 该参数与关联的 CommandName
    /// 一起被传递到 Command 事件。
    /// </param> 
    public void AddShopCart(DataListCommandEventArgs e)
    {
        //if (Session["UserName"] == null)
        //{
        //    Response.Redirect("Default.aspx");
        //}
        /*判断是否登录*/
        ST_check_Login();
        Hashtable hashCar;用哈希表来当购物车哈
        if (Session["ShopCart"] == null)
        {
             //如果用户没有分配购物车
            hashCar = new Hashtable();         //新生成一个
            hashCar.Add(e.CommandArgument, 1); //添加一个商品
            Session["ShopCart"] = hashCar;     //分配给用户
        }
        else
        {
            //用户已经有购物车
            hashCar = (Hashtable)Session["ShopCart"];//得到购物车的hash表
            if (hashCar.Contains(e.CommandArgument))//购物车中已有此商品,商品数量加1
            {
                int count = Convert.ToInt32(hashCar[e.CommandArgument].ToString());//得到该商品的数量
                hashCar[e.CommandArgument] = (count + 1);//商品数量加1
            }
            else
                hashCar.Add(e.CommandArgument, 1);//如果没有此商品,则新添加一个项
        }

    }


   }

 

购物车管理页面

用户与购物车对应关系,用session

购物车中商品存放结构,哈希表(商品名,个数)对

 

1个table显示总价格,1个gridview显示用户购买的商品信息,4个链接按钮,执行,更新,清空,继续,前往服务台的操作


        <asp:GridView ID="gvShopCart" DataKeyNames ="BookID"   runat="server"  AutoGenerateColumns="False"  AllowPaging="True" OnPageIndexChanging="gvShopCart_PageIndexChanging" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" >
                                 <Columns>
                                     <asp:BoundField DataField="No" HeaderText="序号" ReadOnly="True">
                                         <ItemStyle HorizontalAlign="Center" />
                                         <HeaderStyle HorizontalAlign="Center" />
                                     </asp:BoundField>  


                                      <asp:BoundField DataField="BookID" HeaderText="商品ID" ReadOnly="True">
                                         <ItemStyle HorizontalAlign="Center" />
                                         <HeaderStyle HorizontalAlign="Center" />
                                     </asp:BoundField>    
 

                               
                                     <asp:BoundField DataField="BookName" HeaderText="商品名称" ReadOnly="True">
                                      <ItemStyle HorizontalAlign="Center" />
                                      <HeaderStyle HorizontalAlign="Center" />
                                     </asp:BoundField> 
                                     <asp:TemplateField HeaderText="数量">


                          可以加控件自己的事件也          <ItemTemplate >
                                       <asp:TextBox ID="txtNum" runat="server" Text =<%#Eval("Num") %>
Width =60px  OnTextChanged="txtNum_TextChanged"></asp:TextBox>
                                       <asp:RegularExpressionValidator
                                ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtNum"
                                ErrorMessage="×" ValidationExpression="^\+?[1-9][0-9]*$"></asp:RegularExpressionValidator>
                                </ItemTemplate>
                                </asp:TemplateField>
                                   
                                     <asp:TemplateField HeaderText =单价>
                                         <HeaderStyle HorizontalAlign=Center />
                                         <ItemStyle HorizontalAlign =Center />
                                         <ItemTemplate >
                                            <%#Eval("price")%>¥
                                         </ItemTemplate>   
                                     </asp:TemplateField>


                                    <asp:TemplateField HeaderText =总价>
                                         <HeaderStyle HorizontalAlign=Center />
                                         <ItemStyle HorizontalAlign =Center />
                                         <ItemTemplate >
                                            <%#Eval("totalPrice")%>¥
                                         </ItemTemplate>  
  
                                     </asp:TemplateField>

 


                                     <asp:TemplateField>
                                         <HeaderStyle HorizontalAlign=Center />
                                         <ItemStyle HorizontalAlign =Center />
                                         <ItemTemplate >
                                             <asp:LinkButton ID="lnkbtnDelete" runat="server" CommandArgument ='<%#Eval("BookID") %>' OnCommand ="lnkbtnDelete_Command">删除</asp:LinkButton>
                                         </ItemTemplate>   
                                     </asp:TemplateField>
                                     
                                 </Columns>
                                 <FooterStyle BackColor="Tan" />
                                 <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
                                 <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
                                 <HeaderStyle BackColor="Tan" Font-Bold="True" />
                                 <AlternatingRowStyle BackColor="PaleGoldenrod" />
                                </asp:GridView>
       </td>
       </tr>
       <tr align =left valign =top  >
        <td align="center"  >
                                    <asp:LinkButton ID="lnkbtnUpdate" runat="server" OnClick="lnkbtnUpdate_Click">更新购物车</asp:LinkButton>
                                    &nbsp;<asp:LinkButton ID="lnkbtnClear" runat="server" OnClick="lnkbtnClear_Click" >清空购物车</asp:LinkButton>
                                    <asp:LinkButton ID="lnkbtnContinue" runat="server" OnClick="lnkbtnContinue_Click" >继续购物</asp:LinkButton> 
                                    <asp:LinkButton ID="lnkbtnCheck" runat="server" OnClick="lnkbtnCheck_Click" >前往服务台</asp:LinkButton>
         </td>

 后台

public partial class shopCart : System.Web.UI.Page
{
    CommonClass ccObj = new CommonClass();
    DBClass dbObj = new DBClass();
    string strSql;
    DataTable dtTable;
    Hashtable hashCar;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            /*判断是否登录*/
            ST_check_Login();
            if (Session["ShopCart"] == null)
            {
                //如果没有购物,则给出相应信息,并隐藏按钮
                this.labMessage.Text = "您还没有购物!";
                this.labMessage.Visible = true;        //显示提示信息
                this.lnkbtnCheck.Visible = false;      //隐藏“前往服务台”按钮
                this.lnkbtnClear.Visible = false;      //隐藏“清空购物车”按钮
                this.lnkbtnContinue.Visible = false;   //隐藏“继续购物”按钮
            }
            else
            {
                hashCar = (Hashtable)Session["ShopCart"]; //获取其购物车
                if (hashCar.Count == 0)
                {
                    //如果没有购物,则给出相应信息,并隐藏按钮
                    this.labMessage.Text = "您购物车中没有商品!";
                    this.labMessage.Visible = true;        //显示提示信息
                    this.lnkbtnCheck.Visible = false;      //隐藏“前往服务台”按钮
                    this.lnkbtnClear.Visible = false;      //隐藏“清空购物车”按钮
                    this.lnkbtnContinue.Visible = false;   //隐藏“继续购物”按钮
                }
                else
                {
                    //设置购物车内容的数据源
                    dtTable = new DataTable();
                    DataColumn column1 = new DataColumn("No");        //序号列
                    DataColumn column2 = new DataColumn("BookID");    //商品ID代号
                    DataColumn column3 = new DataColumn("BookName");  //商品名称
                    DataColumn column4 = new DataColumn("Num");       //数量
                    DataColumn column5 = new DataColumn("price");     //单价
                    DataColumn column6 = new DataColumn("totalPrice");//总价
                    dtTable.Columns.Add(column1);  //添加新列           
                    dtTable.Columns.Add(column2);
                    dtTable.Columns.Add(column3);
                    dtTable.Columns.Add(column4);
                    dtTable.Columns.Add(column5);
                    dtTable.Columns.Add(column6);
                    DataRow row;
                    //对数据表中每一行进行遍历,给每一行的新列赋值
                    foreach (object key in hashCar.Keys)
                    {
                        row = dtTable.NewRow();
                        row["BookID"] = key.ToString();
                        row["Num"] = hashCar[key].ToString();
                        dtTable.Rows.Add(row);
                    }
                    //计算价格
                    DataTable dstable;
                    int i = 1;
                    float price;//商品单价
                    int count;  //商品数量
                    float totalPrice = 0; //商品总价格
                    foreach (DataRow drRow in dtTable.Rows)
                    {
                        strSql = "select BookName,HotPrice from tb_BookInfo where BookID=" + Convert.ToInt32(drRow["BookID"].ToString());
                        dstable = dbObj.GetDataSetStr(strSql, "tbGI");
                        drRow["No"] = i;//序号
                        drRow["BookName"] = dstable.Rows[0][0].ToString();//商品名称
                        drRow["price"] = (dstable.Rows[0][1].ToString());//单价
                        price = float.Parse(dstable.Rows[0][1].ToString());//单价
                        count = Int32.Parse(drRow["Num"].ToString());
                        drRow["totalPrice"] = price * count; //总价
                        totalPrice += price * count; //计算合价
                        i++;
                    }
                    this.labTotalPrice.Text = "总价:" + totalPrice.ToString();  //显示所有商品的价格
                    this.gvShopCart.DataSource = dtTable.DefaultView;   //绑定GridView控件
                    this.gvShopCart.DataKeyNames = new string[] { "BookID" };
                    this.gvShopCart.DataBind();
                }
            }
       
        }
      
    }
    public void ST_check_Login()
    {

        if ((Session["Username"] == null))
        {
            Response.Write("<script>alert('对不起!您不是会员,请先注册!');location='Default.aspx'</script>");
            Response.End();
        }
    }
    public void bind()
    {
        if (Session["ShopCart"] == null)
        {
            //如果没有购物,则给出相应信息,并隐藏按钮
            this.labMessage.Text = "您还没有购物!";
            this.labMessage.Visible = true;        //显示提示信息
            this.lnkbtnCheck.Visible = false;      //隐藏“前往服务台”按钮
            this.lnkbtnClear.Visible = false;      //隐藏“清空购物车”按钮
            this.lnkbtnContinue.Visible = false;   //隐藏“继续购物”按钮
           
        }
        else
        {
            hashCar = (Hashtable)Session["ShopCart"]; //获取其购物车
            if (hashCar.Count == 0)
            {
                //如果没有购物,则给出相应信息,并隐藏按钮
                this.labMessage.Text = "您购物车中没有商品!";
                this.labMessage.Visible = true;        //显示提示信息
                this.lnkbtnCheck.Visible = false;      //隐藏“前往服务台”按钮
                this.lnkbtnClear.Visible = false;      //隐藏“清空购物车”按钮
                this.lnkbtnContinue.Visible = false;   //隐藏“继续购物”按钮
              
            }
            else
            {
                //设置购物车内容的数据源
                dtTable = new DataTable();
                DataColumn column1 = new DataColumn("No");        //序号列
                DataColumn column2 = new DataColumn("BookID");    //商品ID代号
                DataColumn column3 = new DataColumn("BookName");  //商品名称
                DataColumn column4 = new DataColumn("Num");       //数量
                DataColumn column5 = new DataColumn("price");     //单价
                DataColumn column6 = new DataColumn("totalPrice");//总价
                dtTable.Columns.Add(column1);  //添加新列           
                dtTable.Columns.Add(column2);
                dtTable.Columns.Add(column3);
                dtTable.Columns.Add(column4);
                dtTable.Columns.Add(column5);
                dtTable.Columns.Add(column6);
                DataRow row;
                //对数据表中每一行进行遍历,给每一行的新列赋值
                foreach (object key in hashCar.Keys)
                {
                    row = dtTable.NewRow();
                    row["BookID"] = key.ToString();
                    row["Num"] = hashCar[key].ToString();
                    dtTable.Rows.Add(row);
                }
                //计算价格
                DataTable dstable;
                int i = 1;
                float price;//商品单价
                int count;  //商品数量
                float totalPrice = 0; //商品总价格
                foreach (DataRow drRow in dtTable.Rows)
                {
                    strSql = "select BookName,HotPrice from tb_BookInfo where BookID=" + Convert.ToInt32(drRow["BookID"].ToString());
                    dstable = dbObj.GetDataSetStr(strSql, "tbGI");
                    drRow["No"] = i;//序号
                    drRow["BookName"] = dstable.Rows[0][0].ToString();//商品名称
                    drRow["price"] = (dstable.Rows[0][1].ToString());//单价
                    price = float.Parse(dstable.Rows[0][1].ToString());//单价
                    count = Int32.Parse(drRow["Num"].ToString());
                    drRow["totalPrice"] = price * count; //总价
                    totalPrice += price * count; //计算合价
                    i++;
                }
                this.labTotalPrice.Text = "总价:" + totalPrice.ToString();  //显示所有商品的价格
                this.gvShopCart.DataSource = dtTable.DefaultView;   //绑定GridView控件
                this.gvShopCart.DataKeyNames=new string[] {"BookID"};
                this.gvShopCart.DataBind();
            }
        }
           
   
   
    }


   
 protected void lnkbtnUpdate_Click(object sender, EventArgs e)
    {
        hashCar = (Hashtable)Session["ShopCart"];  //获取其购物车
        //使用foreach语句,遍历更新购物车中的商品数量
       
 foreach (GridViewRow gvr in this.gvShopCart.Rows)
        {
            TextBox otb = (TextBox)gvr.FindControl("txtNum"); //找到用来输入数量的TextBox控件
            int count = Int32.Parse(otb.Text);//获得用户输入的数量值
            string BookID = gvr.Cells[1].Text;//得到该商品的ID代
            hashCar[BookID] = count;//更新hashTable表
        }
        Session["ShopCart"] = hashCar;//更新购物车
        Response.Redirect("shopCart.aspx");
    }
    protected void lnkbtnDelete_Command(object sender, CommandEventArgs e)
    {
        hashCar = (Hashtable)Session["ShopCart"];//获取其购物车
        //从Hashtable表中,将指定的商品从购物车中移除,其中,删除按钮(lnkbtnDelete)的CommandArgument参数值为商品ID代号
        hashCar.Remove(e.CommandArgument);
        Session["ShopCart"] = hashCar; //更新购物车
        Response.Redirect("shopCart.aspx");
    }
    protected void lnkbtnClear_Click(object sender, EventArgs e)
    {
        Session["ShopCart"] =null;
        Response.Redirect("shopCart.aspx");
    }
    protected void lnkbtnContinue_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
    protected void lnkbtnCheck_Click(object sender, EventArgs e)
    {
        Response.Redirect("checkOut.aspx");
    }
    protected void gvShopCart_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvShopCart.PageIndex = e.NewPageIndex;
        bind();

    }
   
 protected void txtNum_TextChanged(object sender, EventArgs e)
    {
       
hashCar = (Hashtable)Session["ShopCart"];  //获取其购物车
        foreach (GridViewRow gvr in this.gvShopCart.Rows)
        {

            TextBox otb = (TextBox)gvr.FindControl("txtNum"); //找到用来输入数量的TextBox控件
            int count = Int32.Parse(otb.Text);//获得用户输入的数量值
            string BookID = gvr.Cells[1].Text;//得到该商品的ID代
            hashCar[BookID] = count;//更新hashTable表

        }
        Session["ShopCart"] = hashCar;//更新购物车
        bind();

    }
}

 

后台登陆模块的设计

用了验证码技术

public partial class Manage_Login : System.Web.UI.Page
{
    //创建公共类CommonClass一个新实例对象
    CommonClass ccObj = new CommonClass();
    DBClass dbObj = new DBClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)//判断页面是否是第一次加载
        {
            this.labCode.Text =
ccObj.RandomNum(4);//产生验证码
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        //判断用户是否已输入了必要的信息
        if (this.txtAdminName.Text.Trim() == "" || this.txtAdminPwd.Text.Trim() == "")
        {
            //调用公共类CommonClass中的MessageBox方法
            Response.Write(ccObj.MessageBox("登录名和密码不能为空!"));
        }
        else
        {
            //判断用户输入的验证码是否正确
            if (txtAdminCode.Text.Trim() == labCode.Text.Trim())
            { 
                //定义一个字符串,获取用户信息
            
    string strSql = "select * from tb_Admin where AdminName='"+this.txtAdminName.Text.Trim()+"' and Password='"+this.txtAdminPwd.Text.Trim()+"'";
                DataTable dsTable=dbObj.GetDataSetStr(strSql, "tbAdmin")
;
                //判断用户是否存在
                if (dsTable.Rows.Count > 0)
                {
                  
  Session["AID"] = Convert.ToInt32(dsTable.Rows[0][0].ToString());//保存用户ID
                    Session["AName"] = dsTable.Rows[0][1].ToString();//保存用户名
                    Response.Write("<script language=javascript>window.open('AdminIndex.aspx');window.close();</script>");
                }
                else
                { 
                   
 Response.Write(ccObj.MessageBox("您输入的用户名或密码错误,请重新输入!"));
                }
            }
            else
            {
               
Response.Write(ccObj.MessageBox("验证码输入有误,请重新输入!"));
            }
        }
    }
       
   
protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Write("<script>window.close();
location='javascript:history.go(-1)';</script>");
    }
}

 

商品库存管理

放之文本框用于搜索商品,一个gridview

   <asp:HyperLinkField HeaderText="详细信息" Text="详细信息" DataNavigateUrlFields="BookID" DataNavigateUrlFormatString="EditProduct.aspx?BookID={0}" >
                                <ControlStyle Font-Underline="False" ForeColor="Black" />
                                <ItemStyle HorizontalAlign="Center" />
                            </asp:HyperLinkField>


                       
     <asp:CommandField HeaderText="删除" ShowDeleteButton="True" >
                                <ControlStyle Font-Underline="False" ForeColor="Black" />
                                <ItemStyle HorizontalAlign="Center" />
                            </asp:CommandField>

 

public partial class Manger_Product : System.Web.UI.Page
{
    CommonClass ccObj = new CommonClass();
    DBClass dbObj = new DBClass();
    GoodsClass gcObj = new GoodsClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //判断是否已点击“搜索”按钮
            ViewState["search"] = null;
           gvBind();//显示商品信息
       }
    }
    //通过商品类别号,获取商品名
    public string GetClassName(int IntClassID)
    {
        string strClassName = gcObj.GetClass(IntClassID);
        return strClassName;
    }
    public String GetVarStr(string strHotPrice)
    {
        return ccObj.VarStr(strHotPrice, 2);
    }
    /// <summary>
    /// 绑定所有商品的信息
    /// </summary>
    public void gvBind()
    {
        string strSql = "select * from tb_BookInfo";
        //调用公共类中的GetDataSetStr方法执行SQL语句,返回数据源的数据表
        DataTable dsTable = dbObj.GetDataSetStr(strSql, "tbBI");
        this.gvGoodsInfo.DataSource = dsTable.DefaultView;
        this.gvGoodsInfo.DataKeyNames = new string[] { "BookID"};
        this.gvGoodsInfo.DataBind();
    }
    /// <summary>
    /// 在搜索中绑定商品信息
    /// </summary>
    public void gvSearchBind()
    {
        DataTable dsTable = gcObj.search(this.txtKey.Text.Trim());
        this.gvGoodsInfo.DataSource = dsTable.DefaultView;
        this.gvGoodsInfo.DataKeyNames = new string[] { "BookID" };
        this.gvGoodsInfo.DataBind();

    }

    protected void gvGoodsInfo_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvGoodsInfo.PageIndex = e.NewPageIndex;
        if (ViewState["search"] != null)
        {
            gvSearchBind();//绑定查询后的商品信息
        }
        else
        {
            gvBind();//绑定所有商品信息
        }
    }

    protected void gvGoodsInfo_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int IntBookID = Convert.ToInt32(gvGoodsInfo.DataKeys[e.RowIndex].Value); //获取商品代号
        string strSql = "select count(*) from tb_Detail where BookID=" + IntBookID;
        SqlCommand myCmd = dbObj.GetCommandStr(strSql);
        //判断商品是否能被删除(如:在明细订单中,包含该商品的ID代号)
        if (Convert.ToInt32(dbObj.ExecScalar(myCmd)) > 0)
        {
            Response.Write(ccObj.MessageBox("该商品正被使用,无法删除!"));
        }
        else
        {
            //删除指定的商品信息
            string strDelSql = "delete from tb_BookInfo where BookID=" + IntBookID;
            SqlCommand myDelCmd = dbObj.GetCommandStr(strDelSql);
            dbObj.ExecNonQuery(myDelCmd);
            //对商品进行重新绑定
            if (ViewState["search"] != null)
            {
                gvSearchBind();//绑定查询后的商品信息
            }
            else
            {
                gvBind();//绑定所有商品信息
            }

        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //将ViewState["search"]对象值1
        ViewState["search"] = 1;
        gvSearchBind();//绑定查询后的商品信息
    }
}

 

-


 

  销售订单管理模块设计

所有订单分为 未确认、已确认、未发生、已发货、未归档、已归档

 

根据订单号、收获人等信息搜索,在gridview中按管理会有详细页面出现了,哈哈。

详细页面可以打印啊。

  <asp:TemplateField HeaderText="管理">
                             <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
         <ItemStyle HorizontalAlign="Center" ></ItemStyle>
         <ItemTemplate>
          <a href='OrderModify.aspx?OrderID=<%# DataBinder.Eval(Container.DataItem, "OrderID") %>'>
           管理</a>
         </ItemTemplate>           
                        </asp:TemplateField>
                            <asp:CommandField ShowDeleteButton="True"  HeaderText="删除" />

以下代码学学如果状态很多的话,的选择方法。

 

public partial class Manage_OrderList : System.Web.UI.Page
{
    CommonClass ccObj = new CommonClass();
    DBClass dbObj = new DBClass();
    OrderClass ocObj = new OrderClass();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            /*判断是否登录*/
            ST_check_Login();
            //判断是否已点击“搜索”按钮
            ViewState["search"] = null;
            pageBind(); //绑定订单信息
        }
    }
    public void ST_check_Login()
    {

        if ((Session["AName"] == null))
        {
            Response.Write("<script>alert('对不起!您不是管理员,无权限浏览此页!');location='../Default.aspx'</script>");
            Response.End();
        }
    }
    //绑定货品总额
    public string GetVarGF(string strGoodsFee)
    {
        return ccObj.VarStr(strGoodsFee, 2);
    }
    //绑定运费
    public string GetVarSF(string strShipFee)
    {
        return ccObj.VarStr(strShipFee,2);
    }
    //绑定总金额
    public string GetVarTP(string strTotalPrice)
    {
        return ccObj.VarStr(strTotalPrice,2);
    }
    public string GetStatus(int IntOrderID)
    {
        string strSql = "select (case IsConfirm when '0' then '未确认' when '1' then '已确认' end ) as IsConfirm";
        strSql +=",(case IsSend when '0' then '未发货' when '1' then '已发货' end ) as IsSend";
        strSql +=",(case IsEnd when '0' then '未归档' when '1' then '已归档' end ) as IsEnd ";
        strSql +="  from tb_OrderInfo where OrderID="+IntOrderID;
        DataTable dsTable = dbObj.GetDataSetStr(strSql, "tbOI");
        return (dsTable.Rows[0][0].ToString() + "|" + dsTable.Rows[0][1].ToString() + "<Br>" + dsTable.Rows[0][2].ToString());
    }
    public string GetAdminName(int IntOrderID)
    {
        string strSql = "select AdminName from tb_Admin ";
        strSql += "where AdminID=(select AdminID from tb_OrderInfo";
        strSql += " where OrderID='"+IntOrderID+"')";
        SqlCommand myCmd=dbObj.GetCommandStr(strSql);
        string strAdminName=(dbObj.ExecScalar(myCmd).ToString());
        if(strAdminName =="")
        {
            return "无";
        }
        else
        {
            return strAdminName;
        }
    }
    /// <summary>
    /// 获取指定订单的信息
    /// </summary>
    string strSql;
    public void pageBind()
    {
        strSql ="select * from tb_OrderInfo where ";
        //获取Request["OrderList"]对象的值,确定查询条件
        string strOL=Request["OrderList"].Trim();
        switch (strOL)
        {
            case "00"://表示未确定
                strSql +="IsConfirm=0";
                break;
            case "01"://表示已确定
                 strSql +="IsConfirm=1";
                break;
            case "10": //表示未发货
                 strSql +="IsSend=0";
                break;
            case "11"://表示已发货
                 strSql +="IsSend=1";
                break;
            case "20": //表示收货人未验收货物
                 strSql +="IsEnd=0";
                break;
            case "21": //表示收货人已验收货物
                 strSql +="IsEnd=1";
                break;
            default :
                break;
        }
        strSql +="  order by OrderDate Desc";
        //获取查询信息,并将其绑定到GridView控件中
        DataTable dsTable = dbObj.GetDataSetStr(strSql, "tbOI");
        this.gvOrderList.DataSource = dsTable.DefaultView;
        this.gvOrderList.DataKeyNames = new string[] { "OrderID"};
        this.gvOrderList.DataBind();
    }
    /// <summary>
    /// 获取符合条件的订单信息
    /// </summary>
    public void gvSearchBind()
    {
        int IntOrderID = 0; //输入订单号
        int IntNF=0;        //判断是否输入收货人
        string strName="";  //输入收货人名
        int IntIsConfirm=0 ;//是否确认
        int IntIsSend=0 ;   //是否发货
        int IntIsEnd =0;    //是否归档
        if (this.txtKeyword.Text == "" && this.txtName.Text == "" && this.ddlConfirmed.SelectedIndex == 0 && this.ddlFinished.SelectedIndex == 0 && this.ddlShipped.SelectedIndex == 0)
        {
            pageBind();
        }
        else
        { 
            if (this.txtKeyword.Text != "")
            {
                IntOrderID = Convert.ToInt32(this.txtKeyword.Text.Trim());
            }
            if (this.txtName.Text != "")
            {
                IntNF = 1;
                strName = this.txtName.Text.Trim();
            }
            IntIsConfirm = this.ddlConfirmed.SelectedIndex;
            IntIsSend = this.ddlShipped.SelectedIndex;
            IntIsEnd =this.ddlFinished.SelectedIndex;
            DataTable dsTable = ocObj.ExactOrderSearch(IntOrderID, IntNF, strName, IntIsConfirm, IntIsSend, IntIsEnd);
            this.gvOrderList.DataSource = dsTable.DefaultView;
            this.gvOrderList.DataKeyNames = new string[] { "OrderID"};
            this.gvOrderList.DataBind();
        }
    }

    protected void gvOrderList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvOrderList.PageIndex = e.NewPageIndex;
        if (ViewState["search"] == null)
        {
            pageBind();//绑定所有订单信息
        }
        else
        {
            gvSearchBind();//绑定查询后的订单信息
       
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //将ViewState["search"]对象值1
        ViewState["search"] = 1;
        gvSearchBind();//绑定查询后的订单信息
    }
    protected void gvOrderList_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string strSql = "select * from tb_OrderInfo where ( IsConfirm=0 or IsEnd=1 ) and OrderID=" + Convert.ToInt32(gvOrderList.DataKeys[e.RowIndex].Value);
        //判断该订单是否已被确认或归档,如果已被确认但未归档,不能删除该订单
        if (dbObj.GetDataSetStr(strSql, "tbOrderInfo").Rows.Count > 0)
        {
            //删除订单表中的信息
            string strDelSql = "delete from tb_OrderInfo where OrderId=" + Convert.ToInt32(gvOrderList.DataKeys[e.RowIndex].Value);
            SqlCommand myCmd = dbObj.GetCommandStr(strDelSql);
            dbObj.ExecNonQuery(myCmd);
            //删除订单详细表中的信息
            string strDetailSql = "delete from tb_Detail where OrderId=" + Convert.ToInt32(gvOrderList.DataKeys[e.RowIndex].Value);
            SqlCommand myDCmd = dbObj.GetCommandStr(strDetailSql);
            dbObj.ExecNonQuery(myDCmd);
        }
        else
        {
            Response.Write(ccObj.MessageBox("该订单还未归档,无法删除!"));
            return;       
        }
        //重新绑定
        if (ViewState["search"] == null)
        {
            pageBind();
        }
        else
        {
            gvSearchBind();

        }
    }
}

 

 <SCRIPT language="JavaScript">
  function printPage()
  {
   eval("printOrder" + ".style.display=\"none\";");
   window.print();
  }
  </SCRIPT>

<SPAN id="printOrder"><input type="button" onclick="printPage()" value="打 印" style="BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; BORDER-LEFT: #000000 1px solid; WIDTH: 69px; BORDER-BOTTOM: #000000 1px solid; HEIGHT: 22px" id="Button1"></SPAN></td>

posted @ 2009-04-15 00:02  minmin8110  阅读(964)  评论(0)    收藏  举报