62,072
社区成员
发帖
与我相关
我的任务
分享
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptCart" runat="server" OnItemCommand="rptCart_ItemCommand">
<HeaderTemplate><ul></HeaderTemplate>
<ItemTemplate>
<li><asp:LinkButton ID="btnProuduct" runat="server" CommandName="SetTop" Text='<%# Eval("Name") %>' /></li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
<asp:TextBox ID="editProduct" runat="server" />
<asp:Button ID="btnAdd" runat="server" Text="Add product to cart." OnClick="btnAdd_Click" />
</div>
</form>
public partial class Default2 : System.Web.UI.Page
{
private CProductQueue _queue = null;
/// <summary>
/// Use session to record the custmolized items.
/// </summary>
protected CProductQueue Queue
{
get
{
if (Session["Queue"] == null)
{
_queue = new CProductQueue(3);
Session["Queue"] = _queue;
}
else
{
_queue = Session["Queue"] as CProductQueue;
}
return _queue;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindRepeater();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Queue.Push(new CProduct(editProduct.Text.Trim()));
BindRepeater();
}
protected void rptCart_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "SetTop":
Queue.SetTop(e.Item.ItemIndex);
break;
}
BindRepeater();
}
private void BindRepeater()
{
rptCart.DataSource = Queue.Products;
rptCart.DataBind();
}
}
public class CProduct
{
private string _name = "";
public string Name
{
get { return _name; }
set { _name = value; }
}
public CProduct(string name)
{
_name = name;
}
public override string ToString()
{
return string.Format("Product: Name={1}", _name);
}
}
public class CProductQueue
{
private ArrayList listProducts = null;
private int _maxLength;
public CProductQueue(int maxLength)
{
listProducts = new ArrayList();
_maxLength = maxLength;
}
public CProductQueue()
{
_maxLength = 10;
}
public CProduct this[int index]
{
get { return IsIndexValid(index) ? listProducts[index] as CProduct : null ; }
set
{
if (IsIndexValid(index))
{
listProducts[index] = value;
}
}
}
public ArrayList Products
{
get
{
return listProducts;
}
}
public void Push(CProduct prodcut)
{
// Inset at first position.
listProducts.Insert(0, prodcut);
if (listProducts.Count > _maxLength)
{
// Remove the last one if the length exceeds.
listProducts.RemoveAt(_maxLength);
}
}
/// <summary>
/// Sets the product with the specific index top of the query.
/// </summary>
public void SetTop(int index)
{
if (IsIndexValid(index) && index > 0)
{
CProduct origin = listProducts[index] as CProduct;
CProduct product = new CProduct(origin.Name);
listProducts.RemoveAt(index);
Push(product);
}
}
private bool IsIndexValid(int index)
{
return (index < listProducts.Count && index >= 0);
}
}