如何存储记录使用的ViewState [英] How to store record using ViewState
问题描述
现在有2个按钮,让我们分别称之为Button1的和的Button2。
如果我点击Button1的商店1的ViewState [记录];同样,如果我点击Button2的
店2的ViewState [记录]等。
Now there are 2 buttons, let's call them "Button1" and "Button2" respectively. If I click "Button1", store "1" in ViewState["Record"]; also, if I click "Button2", store "2" in ViewState["Record"], etc.
当我点击Button1⟶Button1⟶Button2⟶Button2,我预期的结果是:在ViewState中[记录],还有一个记录列表,像
When I click Button1⟶Button1⟶Button2⟶Button2, my expected result is: in ViewState["Record"], there are a list of records, like
[1,1,2,2].
下面是我的单击事件code:
Here is my click event code:
protected void Button1_Click(object sender, EventArgs e)
{
ViewState.Add("Record", "1");
}
protected void Button2_Click(object sender, EventArgs e)
{
ViewState.Add("Record", "2");
}
//show the viewstate result
protected void ShowResult(object sender, EventArgs e)
{
for (int i = 1; i <= 4; i++)
{
Label.Text += ViewState["Record"];
}
}
显示2222,而不是1122。
我怎样才能code如何解决?
It shows "2222" instead of "1122". How can I code to resolve it?
推荐答案
当您添加值实际上它并不增加录音键,只是把一个值录音键。你总是看到你的循环最后的附加价值。
When you add Record key a value actually it not adds, just puts a value Record key. You always see last added value on your loop.
您应该添加一个列表来ViewState的并增加其价值上市。
You should add a List to ViewState and add value to list.
添加此属性。
protected List<long> ViewStateList
{
get{ if(ViewState["Record"] == null) ViewState["Record"] = new List<long>();
return (List<long>)ViewState["Record"] }
}
和使用像
protected void Button1_Click(object sender, EventArgs e)
{
ViewStateList.Add(1);
}
循环
protected void ShowResult(object sender, EventArgs e)
{
foreach(long item in ViewStateList)
{
Label.Text += item.ToString();
}
}
这篇关于如何存储记录使用的ViewState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!