-
굳이 제목을 붙이자면 상품 카트에 추가하기?예전 글들/.NET, C# 2010. 12. 27. 13:30반응형
컴파일하면 실행은 되는데 문제점이 많구만
1. 우선 상품 리스트가 너무 많이 나오는데 조금 줄여야겠다. 이건 사이즈를 줄이고, 그 옆에 스크롤을 놓던가 아니면 페이지를 저장하는 걸 하면되려나? 근데 어찌해야하는건지....
2. 리스트에서 상품 클릭하면 상품 정보 뜨는 ProductInfo.aspx 파일 만들어봐야겠구만
3. 상품을 카트에 추가하면 상품 이름도 뜨게해야겠고, 삭제해보면 삭제가 안되는데 이것도 고쳐야겠군
4. 무조건 포스트 백 시키는 것이 아니라 상품 목록을 다 고르거나 아니면 사용자가 포스트백 한다는 느낌이 안들도록 할 수 없나? 이건 뭐 뭐하나 선택하면 화면이 다시 고쳐지니 영 할맛이 안나네..
위 문제 말고도 뭐 이것저것 많을 테지만...우선 된다는 것에 -_-; 이제 슬슬 잡아볼까나~
디비 파일은 윈도우 서버에서 공짜로!! 제공해주는 northwind 데이터
아래 싸이트에서 다운 가능함.
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en
소스 원본: Programming ASP.NET의 Chaper 6의 ShoppingCart 소스
소스 파일
우선 디자인 파일이라 할 수 있는 Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication11._Default" Debug="true"%><!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>a:hover {color:Red;}</style>
</head>
<body vlink="black" link="black">
<h2>Northwind Shopping Center</h2>
<form id="form1" runat="server">
<table><tr>
<td valign="top" height="100%">
<asp:LinkButton runat="server" ID="ResetOrderButton" Text="Default Sorting..."
Font-Names="verdana" Font-Size="8pt" OnClick="ResetOrder" />
<asp:DataGrid runat="server" ID="grid"
AutoGenerateColumns="false"
GridLines="None"
CellPadding="2"
Font-Names="verdana"
Font-Size="8pt"
DataKeyField="ProductID"
allowsorting="true"
PageSize="8"
onitemcommand="ItemCommand"
onitemcreated="grid_ItemCreated"
onitemdatabound="grid_ItemDataBound"
onpageindexchanged="grid_PageIndexChanged"
onselectedindexchanged="grid_SelectedIndexChanged"
onsortcommand="grid_SortCommand"
>
<HeaderStyle BackColor="Gray" Font-Bold="true" ForeColor="White"
Height="200%" HorizontalAlign="Center" />
<AlternatingItemStyle BackColor="#eeeeee" />
<PagerStyle BackColor="Gray" Font-Bold="true" ForeColor="White"
Height="200%" Mode="NumericPages" />
<SelectedItemStyle BackColor="Cyan" />
<Columns>
<asp:ButtonColumn DataTextField="ProductName" HeaderText="Product"
SortExpression="ProductName"
CommandName="select">
<ItemStyle Width="200px" />
</asp:ButtonColumn>
<asp:BoundColumn DataField="QuantityPerUnit" HeaderText="Packaging" />
<asp:BoundColumn DataField="UnitPrice"
SortExpression="UnitPrice"
HeaderText="Price" DataFormatString="{0:c}">
<ItemStyle Width="80px" HorizontalAlign="Right" />
</asp:BoundColumn>
<asp:TemplateColumn HeaderText="Order">
<ItemStyle Width="60px" HorizontalAlign="Right" />
<ItemTemplate>
<asp:TextBox runat="server" ID="qty" Width="20px" MaxLength="1" Font-Size="X-Small"
BackColor="Yellow" BorderStyle="Solid" Text="1" />
<asp:LinkButton ID="Linkbutton1" runat="server" CommandName="AddToCart"
Text="Add to Cart" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</td>
<td valign="top">
<iframe runat="server" id="ProductView" title="ProductView" frameborder="0" height="100%"
style="border:solid 1px;" ></iframe>
</td>
</tr></table><h3>Shopping Cart</h3>
<asp:LinkButton runat="server" ID="ClearCartButton" Text="Clear cart..."
Font-Names="verdana" Font-Size="8px" OnClick="ClearCart" />
<asp:DataGrid runat="server" ID="cartGrid"
AutoGenerateColumns="false"
GridLines="None"
ShowFooter="true"
CellPadding="2"
Font-Name="verdaba"
Font-Size="8px"
PageSize="4"
AllowPaging="true" onitemcommand="ItemCommand"
onitemcreated="cartGrid_ItemCreated" onpageindexchanged="cartGrid_PageIndexChanged"
>
<HeaderStyle BackColor="Gray" Font-Bold="true" ForeColor="White" Height="200%" />
<FooterStyle BackColor="Brown" Font-Bold="true" ForeColor="White" />
<PagerStyle BackColor="Gray" ForeColor="Yellow" Font-Names="wedbings"
Font-Size="10pt" NextPageText="4" PrevPageText="3" />
<Columns>
<asp:BoundColumn DataField="quantity" HeaderText="Product">
<ItemStyle Width="220px" />
</asp:BoundColumn>
<asp:BoundColumn DataField="price" HeaderText="Price" DataFormatString="{0:c}" >
<ItemStyle Width="50px" HorizontalAlign="Right" />
</asp:BoundColumn>
<asp:ButtonColumn Text="Remove" CommandName="RemoveFormCart" >
<ItemStyle Width="70px" HorizontalAlign="Right" />
</asp:ButtonColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</html>
자~다음은 기능입니다. Default.aspx.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.SqlClient;
using System.Data;
using System.Drawing;
namespace WebApplication11
{
public partial class _Default : System.Web.UI.Page
{
private string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + "C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\northwind_Data.mdf" + ";Integrated Security=True;Connect Timeout=30;User Instance=True";
private string cmdText = "SELECT ProductID, ProductName, UnitPrice, QuantityPerUnit, UnitsInStock FROM Products";
private DataTable m_cart;
private int m_currentSelectedIndex = -1;
private string m_DESC = " DESC";protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
m_cart = new DataTable();
m_cart.Columns.Add("Quantity", typeof(int));
m_cart.Columns.Add("ProductName", typeof(string));
m_cart.Columns.Add("Price", typeof(decimal));
Session["NorthwindShoppingCart"] = m_cart;LoadDataFromDatabase();
BindData();
}
else
m_cart = (DataTable)Session["NorthwindShoppingCart"];ClearCartButton.Visible = m_cart.Rows.Count > 0;
}private void BindData()
{
DataTable data = (DataTable) Cache["AppData"];
DataView dv = data.DefaultView;
dv.Sort = (String)ViewState["DataSortExpression"];
grid.DataSource = dv;
grid.DataBind();
}private void LoadDataFromDatabase()
{
DataTable data = ExecuteQuery(cmdText, connString);
Cache["AppData"] = data;
}private DataTable ExecuteQuery(string cmdText, string connString)
{
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, connString);
DataTable data = new DataTable();
adapter.Fill(data);
return data;
}protected void grid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
//Cancels the selection
grid.SelectedIndex = -1;
ProductView.Attributes["Stc"] = "";grid.CurrentPageIndex = e.NewPageIndex;
BindData();
}protected void grid_SelectedIndexChanged(object sender, EventArgs e)
{
if (m_currentSelectedIndex == grid.SelectedIndex)
{
grid.SelectedIndex = -1;
return;
}
SelectItem();
}private void SelectItem()
{
int productID = (int)grid.DataKeys[grid.SelectedIndex];
ProductView.Attributes["Src"] = String.Format("productinfo.aspx?id={0}", productID);
}protected void ClearCart(object sender, EventArgs e)
{
if (m_cart == null)
m_cart = (DataTable)Session["NorthwindShoppingCart"];
m_cart.Rows.Clear();RefreshCart();
}private void RefreshCart()
{
// Make the clear cart button visible if needed
ClearCartButton.Visible = m_cart.Rows.Count > 0;Session["NothwindShoppingCart"] = m_cart;
if (m_cart.Rows.Count == 0)
cartGrid.DataSource = null;
else
cartGrid.DataSource = m_cart;cartGrid.DataBind();
}protected void ItemCommand(object sender, DataGridCommandEventArgs e)
{
switch (e.CommandName)
{
case "AddToCart":
AddToCart(e.Item, e.Item.ItemIndex);
break;
case "RemoveFromCart":
RemoveFromCart(e.Item.ItemIndex);
break;
case "select":
m_currentSelectedIndex = grid.SelectedIndex;
break;
}
}private void RemoveFromCart(int rowIndex)
{
if (m_cart == null)
m_cart = (DataTable)Session["NorthwindShoppingCart"];int rowsInLastPage = m_cart.Rows.Count % cartGrid.PageSize;
m_cart.Rows.RemoveAt(rowIndex);if (rowsInLastPage == 1 && cartGrid.CurrentPageIndex > 0)
cartGrid.CurrentPageIndex -= 1;
RefreshCart();
}private void AddToCart(DataGridItem item, int rowIndex)
{
DataTable data = (DataTable)Cache["AppData"];
DataRow row = m_cart.NewRow();int key = (int)grid.DataKeys[rowIndex];
DataRow[] rows = data.Select(grid.DataKeyField + "=" + key.ToString());
DataRow tableRow = rows[0];// Get the quantity to order from the textBox
int defaultQuantity = 1;
TextBox ctl = (TextBox)item.FindControl("qty");
if (ctl != null)
defaultQuantity = Convert.ToInt32(ctl.Text);row["Quantity"] = defaultQuantity;
row["ProductName"] = tableRow["ProductName"];
row["Price"] = (decimal)(defaultQuantity * Convert.ToDecimal(tableRow["UnitPrice"]));
m_cart.Rows.Add(row);// Select the item
grid.SelectedIndex = rowIndex;
SelectItem();RefreshCart();
}protected void grid_SortCommand(object source, DataGridSortCommandEventArgs e)
{
string newExpr = e.SortExpression;
string oldExpr = (string)ViewState["DataSortExpression"];
if (oldExpr == newExpr)
ViewState["DataSortExpression"] = newExpr + m_DESC;
else
ViewState["DataSortExpression"] = newExpr;BindData();
}protected void grid_ItemCreated(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
switch (itemType)
{
case ListItemType.Header:
SetupHeader(e);
break;
}
}private void SetupHeader(DataGridItemEventArgs e)
{
string sortExpr = (string)ViewState["DataSortExpression"];
if (sortExpr == null)
return;bool isDesc = sortExpr.EndsWith(m_DESC);
string pureSortExpr = sortExpr.Replace(m_DESC, "");for (int i = 0; i < grid.Columns.Count; i++)
{
// Draw the glyph to reflect sorting direction
string colSortExpr = grid.Columns[i].SortExpression;
if (pureSortExpr == colSortExpr && colSortExpr != "")
{
TableCell cell = e.Item.Cells[i];
Label lblSorted = new Label();
lblSorted.Font.Name = "wedbings";
lblSorted.Font.Size = FontUnit.XSmall;
lblSorted.Text = (isDesc ? "6" : "5");
cell.Controls.Add(lblSorted);
}
}
}protected void grid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
ListItemType itemType = e.Item.ItemType;
if (itemType == ListItemType.Item || itemType == ListItemType.AlternatingItem)
{
DataRowView drv = (DataRowView)e.Item.DataItem;
((WebControl)e.Item.Cells[0].Controls[0]).ToolTip = drv["unitsinstock"].ToString() + "units in stock";
}
}protected void cartGrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
{
cartGrid.CurrentPageIndex = e.NewPageIndex;
RefreshCart();
}protected void cartGrid_ItemCommand(object source, DataGridCommandEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
if (m_cart == null)
m_cart = (DataTable)Session["NorthwindShoppingCart"];if (m_cart.Rows.Count == 0)
return;
int totalItems = Convert.ToInt32(m_cart.Compute("Sum(quantity)", "")); //이거 뭘까요?
decimal totalPrice = Convert.ToDecimal(m_cart.Compute("Sum(price)", ""));
e.Item.Cells[0].Text = totalItems.ToString();
e.Item.Cells[2].HorizontalAlign = HorizontalAlign.Right;
e.Item.Cells[2].Text = String.Format("{0:c}", totalPrice);
return;
}if (e.Item.ItemType == ListItemType.Pager)
{
if (cartGrid.PagerStyle.Mode == PagerMode.NextPrev)
{
TableCell pager = e.Item.Cells[0];
Label ctl = new Label();
ctl.Font.Name = "verdana";
ctl.Font.Size = FontUnit.Point(8);
ctl.ForeColor = Color.White;
ctl.Text = " <b>Page" + (1 + cartGrid.CurrentPageIndex).ToString() + "</b> ";
pager.Controls.AddAt(1, ctl);
}
}
}protected void cartGrid_ItemCreated(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Footer)
{
if (m_cart == null)
m_cart = (DataTable)Session["NorthwindShoppingCart"];
if (m_cart.Rows.Count == 0)
return;
int totalItem = Convert.ToInt32(m_cart.Compute("Sum(Quantity)", ""));
decimal totalPrice = Convert.ToDecimal(m_cart.Compute("Sum(Price)", ""));
e.Item.Cells[0].Text = totalItem.ToString();
e.Item.Cells[2].HorizontalAlign = HorizontalAlign.Right;
e.Item.Cells[2].Text = String.Format("{0:c}", totalPrice);
return;
}
if( e.Item.ItemType == ListItemType.Pager)
{
if (cartGrid.PagerStyle.Mode == PagerMode.NextPrev)
{
TableCell pager = e.Item.Cells[0];
Label ctl = new Label();
ctl.Font.Name = "verdana";
ctl.Font.Size = FontUnit.Point(8);
ctl.ForeColor = Color.White;
ctl.Text = " <b>Page" + (1 + cartGrid.CurrentPageIndex).ToString() + "</b> ";
pager.Controls.AddAt(1, ctl);
}
}
}protected void ResetOrder(object sender, EventArgs e)
{
ViewState["DataSortExpression"] = "";
BindData();
}}
}
반응형'예전 글들 > .NET, C#' 카테고리의 다른 글
aspx.cs 파일에 작성된 함수에서 aspx 파일에 있는 스크립트 접근 하는 방법 (0) 2011.01.11 아래에 있는 ShoppingCart 소스 추가!! ProductInfo 소스 파일 (0) 2010.12.27 데이터베이스 접속하는 방법들 중에 하나랍니다. (0) 2010.12.25 컨트롤 만들기 오류 해결 방법 (0) 2010.11.02 트랜잭션 완성하기 - 데이터 액세스 할때 좀 더 안정성을 높이려면 이런 구조가 좋을 듯 (0) 2010.10.28 댓글