我有一个禁用的文本框,只要点击一个按钮,它的值只增加1,问题是它从1变为2并且就是这样。我希望每次按下按钮都会增加。
namespace StudentSurveySystem
{
public partial class AddQuestions : System.Web.UI.Page
{
int num = 1;
protected void Page_Load(object sender, EventArgs e)
{
QnoTextBox.Text = num.ToString();
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
num += 1;
QnoTextBox.Text = num.ToString();
}
}
}
答案 0 :(得分:8)
Postback intializes the variable num to 1 again
并且您没有获得预期的递增结果,您最好使用文本框值并将值存储在ViewState
中。
protected void ASPxButton1_Click(object sender, EventArgs e)
{
num = int.Parse(QnoTextBox.Text);
num++;
QnoTextBox.Text = num.ToString();
}
使用ViewState
public partial class AddQuestions : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
ViewState["Num"] = "1";
}
protected void ASPxButton1_Click(object sender, EventArgs e)
{
QnoTextBox.Text = ViewState["Num"].ToString();
int num = int.Parse(ViewState["Num"].ToString());
ViewState["Num"] = num++;
}
}