asp.net做个栈的简单例子
要实现的是按 "入栈 ",就有10个数字入栈,
出栈就有这10个数字出栈,
比如入栈是0,1,2,3,4,5,6,7,8,9
出栈是9,8,7,6,5,4,3,2,1,0
我写的有错,麻烦各位抽空看看:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
Label prompt = new Label();
prompt.Text = "请输入数据 ";
TextBox input = new TextBox();
input.Text = "输入要放入栈中的字符 ";
input.Attributes.Add( "onFocus ", "this.value= ' ' ");
//入栈按钮
Button btnPush = new Button();
btnPush.ID = "btnPush ";
btnPush.Text = "入栈 ";
btnPush.Command += new CommandEventHandler(this.btnPush_Click);
//出栈按钮
Button btnPop = new Button();
btnPop.ID = "btnPop ";
btnPop.Text = "出栈 ";
btnPop.Command += new CommandEventHandler(this.btnPop_Click);
//添加控件
this.form1.Controls.Add(prompt);
this.form1.Controls.Add(input);
this.form1.Controls.Add(btnPush);
this.form1.Controls.Add(btnPop);
}
public Stack stack = new Stack();
protected void btnPush_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
stack.Push(i);
}
}
protected void btnPop_Click(object sender, EventArgs e)
{
while (stack.Count > 0)
{
Response.Write(stack.Pop().ToString() + "- ");
}
}
}
[解决办法]
public Stack stack = new Stack();
在这里,已经解释了一切——你的Stack在每次PostBack的时候都重新new,也就不会保持上一次的内容。如果你要Stack在多次PostBack之间持久,你就要把它保存到ViewState。
[解决办法]
把这个改一下:
public Stack stack = new Stack();
改成:
public Stack stack()
{
get
{
if(ViewState[ "stack "] == null)
{
ViewState[ "stack "] = new Stack();
}
return (Stack)ViewState[ "stack "];
}
}