BasharKH
BasharKH

Reputation: 117

Increment the int value in the text box

I have a disabled text box thats' value only increments by one once a button is clicked, the problem is that it goes from 1 to 2 and thats it. I want it to increment everytime i push the button.

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();
        }
    }
}

Upvotes: 2

Views: 7089

Answers (1)

Adil
Adil

Reputation: 148110

Postback intializes the variable num to 1 again and you do not get the expected increamented result, you better you textbox value and store the value in ViewState.

protected void ASPxButton1_Click(object sender, EventArgs e)
{
    num = int.Parse(QnoTextBox.Text);
    num++;
    QnoTextBox.Text = num.ToString();
}

Using 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++;
    }
}

Upvotes: 8

Related Questions