2

我有一个禁用的文本框,一旦单击按钮,其值只会增加一,问题是它从 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();
        }
    }
}
4

1 回答 1

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++;
    }
}
于 2012-12-07T19:26:41.040 回答