天天看點

ASP.NET利用DataList實作從購物車添加商品

前言

VS中的DataList控件可以内嵌按鈕,為建立庫存清單提供了便利。

DataList内嵌按鈕

最近在練習ASP.NET,建立一個購物網站時用到了會話(Session),通過Session将使用者購買的商品資訊臨時存儲下來,實作從庫存中挑選商品的功能。網頁設計如下,左側DataList清單為庫存資訊,右側GridView表格為選中的資訊,通過點選DataList清單中的SelectItem按鈕将對應商品添加到GridView表格。

ASP.NET利用DataList實作從購物車添加商品

DataList表格可以将按鈕内嵌,适合在庫存數目比較大且庫存實時變化的情況下使用。DataList中内嵌的按鈕似乎隻能通過DataList的事件屬性ItemCommand來實作,通過該事件的DataListCommandEventArgs參數可以獲得按鈕對應的資料,代碼如下。

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            int nItemIndex = e.Item.ItemIndex;     //擷取選中項
            this.DataList1.SelectedIndex = nItemIndex;

            BindToinventory();
          
            DataTable dt = (DataTable)DataList1.DataSource;     //從資料庫中擷取該項資訊
            String strID = (dt.Rows[nItemIndex][0]).ToString();
            String strTitle = (dt.Rows[nItemIndex][1]).ToString();
            String strAuthorLastName = (dt.Rows[nItemIndex][2]).ToString();
            String strAuthorFirstName = (dt.Rows[nItemIndex][3]).ToString();
            String strTopic = (dt.Rows[nItemIndex][4]).ToString();
            String strPublisher = (dt.Rows[nItemIndex][5]).ToString();

            DataTable tableSelectedItems;
            tableSelectedItems = (DataTable)Session["tableSelectedItems"];   //從Session擷取已添加表格

            DataRow dr = tableSelectedItems.NewRow();    //添加新行
            dr[0] = strID;
            dr[1] = strTitle;
            dr[2] = strAuthorLastName;
            dr[3] = strAuthorFirstName;
            dr[4] = strTopic;
            dr[5] = strPublisher;

            tableSelectedItems.Rows.Add(dr);

            Session["tableSelectedItems"] = tableSelectedItems;    //将新表格資訊存入Session

            this.GridView1.DataSource = tableSelectedItems;    //重新整理表格
            this.GridView1.DataBind();
        }
           

源碼

aspx檔案:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UseDataList.aspx.cs" Inherits="SessionState.UseDataList" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1 {
            z-index: 100;
            left: 26px;
            position: absolute;
            top: 56px;
            width: 458px;
            height: 788px;
            margin-right: 4px;
        }
        .auto-style2 {
            z-index: 1;
            left: 504px;
            top: 78px;
            position: absolute;
            height: 136px;
            width: 399px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:DataList ID="DataList1"
    runat="server" BackColor="White" BorderColor="#E7E7FF"
    BorderStyle="None" BorderWidth="1px" CellPadding="3"
    GridLines="Horizontal"
    OnItemCommand="DataList1_ItemCommand" Caption="Items in Inventory" CssClass="auto-style1" >
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<SelectedItemStyle BackColor="#738A9C"
      Font-Bold="True" ForeColor="#F7F7F7" />
<AlternatingItemStyle BackColor="#F7F7F7" />
<ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
      <ItemTemplate>
      ID:
      <asp:Label ID="IDLabel"
      runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
      Title:
      <asp:Label ID="TitleLabel"
      runat="server" Text='<%# Eval("Title") %>'></asp:Label><br />
      AuthorLastName:
      <asp:Label ID="AuthorLastNameLabel"
      runat="server" Text='<%# Eval("AuthorLastName")
      %>'></asp:Label><br />
      AuthorFirstName:
      <asp:Label ID="AuthorFirstNameLabel"
      runat="server" Text='<%# Eval("AuthorFirstName")
      %>'></asp:Label><br />
      Topic:
      <asp:Label ID="TopicLabel" runat="server"
      Text='<%# Eval("Topic") %>'></asp:Label><br />
      Publisher:
      <asp:Label ID="PublisherLabel"
      runat="server"

      Text='<%# Eval("Publisher") %>'></asp:Label><br />
      <br />

    <asp:Button ID="SelectItem"

       runat="server" Text="Select Item" />

      &nbsp;
      </ItemTemplate>
         <HeaderStyle BackColor="#4A3C8C" Font-Bold="True"
            ForeColor="#F7F7F7" />
</asp:DataList>


        <br />
        <br />


    </div>
    <asp:GridView ID="GridView1" runat="server" CellPadding="4" 
        EnableModelValidation="True" ForeColor="#333333" GridLines="None" CssClass="auto-style2">
        <AlternatingRowStyle BackColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#EFF3FB" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    </asp:GridView>
    </form>
</body>
</html>
           

cs檔案:

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.Data.Common;

namespace SessionState
{
    public partial class UseDataList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = BindToinventory();
                DataTable tableSelectedItems =
                   this.CreateSelectedItemsTable(dt);
                Session["tableSelectedItems"] = tableSelectedItems;
            }
        }


        protected DataTable GetInventory()
        {
            string strConnection =
            @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="""+ AppDomain.CurrentDomain.BaseDirectory + @"App_Data\ASPNETStepByStep4.mdf"";Integrated Security=True";

            DbProviderFactory f =
               DbProviderFactories.GetFactory("System.Data.SqlClient");

            DataTable dt = new DataTable();
            using (DbConnection connection = f.CreateConnection())
            {         
                connection.ConnectionString = strConnection;

                connection.Open();

                DbCommand command = f.CreateCommand();
                command.CommandText = "Select * from DotNetReferences";
                command.Connection = connection;

                IDataReader reader = command.ExecuteReader();

                dt.Load(reader);
                reader.Close();
                connection.Close();
            }

            return dt;
        }

        protected DataTable BindToinventory()
        {
            DataTable dt;
            dt = this.GetInventory();
            this.DataList1.DataSource = dt;

            this.DataBind();
            return dt;
        }

        protected DataTable CreateSelectedItemsTable(DataTable tableSchema)
        {

            DataTable tableSelectedItemsData = new DataTable();

            foreach (DataColumn dc in tableSchema.Columns)
            {
                tableSelectedItemsData.Columns.Add(dc.ColumnName,
                      dc.DataType);
            }
            return tableSelectedItemsData;

        }



        protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
        {
            int nItemIndex = e.Item.ItemIndex;
            this.DataList1.SelectedIndex = nItemIndex;

            BindToinventory();

            DataTable dt = (DataTable)DataList1.DataSource;
            String strID = (dt.Rows[nItemIndex][0]).ToString();
            String strTitle = (dt.Rows[nItemIndex][1]).ToString();
            String strAuthorLastName = (dt.Rows[nItemIndex][2]).ToString();
            String strAuthorFirstName = (dt.Rows[nItemIndex][3]).ToString();
            String strTopic = (dt.Rows[nItemIndex][4]).ToString();
            String strPublisher = (dt.Rows[nItemIndex][5]).ToString();

            DataTable tableSelectedItems;
            tableSelectedItems = (DataTable)Session["tableSelectedItems"];

            DataRow dr = tableSelectedItems.NewRow();
            dr[0] = strID;
            dr[1] = strTitle;
            dr[2] = strAuthorLastName;
            dr[3] = strAuthorFirstName;
            dr[4] = strTopic;
            dr[5] = strPublisher;

            tableSelectedItems.Rows.Add(dr);

            Session["tableSelectedItems"] = tableSelectedItems;

            this.GridView1.DataSource = tableSelectedItems;
            this.GridView1.DataBind();
        }

    }
}