我在让页面保持状态时遇到问题。默认情况下启用视图状态,但每次单击按钮时它都会重置表单。这是我的代码
protected void Page_Load(object sender, EventArgs e)
{
Levels loadGame = new Levels(currentGame);
int [] gameNums = loadGame.getLevelNums();
int inc = 1;
foreach(int i in gameNums){
if (i != 0)
{
TextBox tb = (TextBox)FindControl("TextBox" + inc);
tb.Text = i.ToString();
tb.Enabled = false;
}
else {
//leave blank and move to next box
}
inc++;
}
这是初始加载
protected void NormalButton_Click(object sender, EventArgs e)
{
clearBoxes();//clear boxes first
setCurrentGame("normal");//setting to normal returns normal answers
Levels loadGame = new Levels(returnCurrentGame());
int[] gameNums = loadGame.getLevelNums();
int inc = 1;
foreach (int i in gameNums)
{
if (i != 0)
{
TextBox tb = (TextBox)FindControl("TextBox" + inc);
tb.Text = i.ToString();
tb.Enabled = false;
}
else
{
//leave blank and move to next box
}
inc++;
}
}
单击此按钮可更改不同框中的数字。
protected void Button1_Click(object sender, EventArgs e)
{
}
然后我有这个空按钮,但每次我点击它,它重置表格,即使我还没有设置它做任何事情。我希望盒子保持不变,我也希望保持这些物体的存活。我不确定我错过了什么,但请指出我正确的方向。提前致谢
答案 0 :(得分:2)
每次加载页面时都会发生Page_Load事件,包括事件驱动的回发(按钮点击等)。
看起来初始化代码在您的Page_Load中,所以当您单击该按钮时它会再次运行。
有两种选择:
第一个选项的代码示例:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack) // Teis is the key line for avoiding the problem
{
Levels loadGame = new Levels(currentGame);
int [] gameNums = loadGame.getLevelNums();
int inc = 1;
foreach(int i in gameNums){
if (i != 0)
{
TextBox tb = (TextBox)FindControl("TextBox" + inc);
tb.Text = i.ToString();
tb.Enabled = false;
}
else {
//leave blank and move to next box
}
inc++;
}
}
}
另外,建议阅读:The ASP.NET Page Lifecycle