首先,您需要关注如何将以前的数据保留在页面上。
从 Post 到 Post,您可以将它们存储在ViewState
ether 上的control
.
正如我所见,在 上保存了以前的状态btn.Text
,这不是很酷,但可以接受。
protected void btnEnter_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// the btn.Text keeps the number of post backs (enters of name).
var Counter = Int32.Parse(btn.Text);
Counter++;
if(Counter >= 5)
{
Label1.Text = "No more studen's names please";
}
else
{
btn.Text = Counter.ToString();
Label1.Text = "Enter Another student's name";
}
}
如您所见,是“存储”柜台中的btn.Text
一个使用它知道许多帖子已经完成。
您可以使用某种方式来存储输入的名称。我更喜欢将它保存在视图状态中,我可以用这段代码来做到这一点。
const string cArrNameConst = "cArr_cnst";
public string[] cArrKeepNames
{
get
{
if (!(ViewState[cArrNameConst] is string[]))
{
// need to fix the memory and added to viewstate
ViewState[cArrNameConst] = new string[5];
}
return (string[])ViewState[cArrNameConst];
}
}
并且使用该代码,您可以在代码上从 0->4 添加任何名称,cArrKeepNames[]
并在回发后拥有它,因为它保持在页面的视图状态。
protected void btnEnter_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
var Counter = Int32.Parse(btn.Text);
// here you save the name in the array
// an magically is saved inside the page on viewstates data
// and you can have it anywhere on code behind.
cArrKeepNames[Counter] = NameFromEditor.Text;
Counter++;
if(Counter >= 5)
{
btn.Enable = false;
Label1.Text = "No more studen's names please";
}
else
{
btn.Text = Counter.ToString();
Label1.Text = "Enter Another student's name";
}
}
像这样的简单代码可以随时读取数组:
foreach (var One in cArrKeepNames)
txtOutput.Text += "<br>" + One;
我对其进行了测试并且运行良好。