Question

In my ASP.NET Web Application, I have a "Next" button control. Each time I click this button, I want the value of ViewState["QNO"] to increase by 1.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            int qno = Convert.ToInt32(ViewState["QNO"]);
            if (ViewState["QNO"] == null)
            {
                ViewState["QNO"] = 1;
            }
            else
            {
                ViewState["QNO"] = qno++;
            }
        }

Code for click event on button:

protected void btnNext_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection(str);
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from QSet where QID='" + ViewState["QNO"] + "'", con);
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            lblNo.Text = "(" + dr.GetValue(0).ToString() + ")";
            lblQues.Text = dr.GetValue(1).ToString();
            Qoptions.Items.Add(dr.GetValue(2).ToString());
            Qoptions.Items.Add(dr.GetValue(3).ToString());
            Qoptions.Items.Add(dr.GetValue(4).ToString());
            Qoptions.Items.Add(dr.GetValue(5).ToString());
        }

        con.Close();
    }
Was it helpful?

Solution

Change your code for Page Load as this:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
                ViewState["QNO"] = 1;
        }
        else
         {
             ViewState["QNO"] = Convert.ToInt32(ViewState["QNO"]) +1;
         }
}

OTHER TIPS

I believe a server side button click causes a PostBack. In your code, you have if (!IsPostBack) then increment by 1. Change to if (IsPostBack) perhaps.

code inside if (!IsPostBack) will only be hit on initial load.

change load code to

if (IsPostBack)
    {
        if (ViewState["QNO"] == null)
        {
            ViewState["QNO"] = 1;
        }
        else
        {
            int qno = Convert.ToInt32(ViewState["QNO"]);
            ViewState["QNO"] = qno++;
        }
    }

The problem is with the assignment of the increment operator. Also, I made few corrections.

    public void IncrementQNO()
    {
        if (ViewState["QNO"] == null)
        {
            ViewState["QNO"] = 1;
        }
        else
        {
            int qno = Convert.ToInt32(ViewState["QNO"]);
            ViewState["QNO"] = ++qno;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
       IncrementQNO();
    }

Just tested this and it works fine.

In your page_load, this line will fail right away:

int qno = Convert.ToInt32(ViewState["QNO"]);

The code is not running in a postback, so anything you pull out of viewstate will, by definition, be null.

You need another code path to initialize "QNO" with 0 if not in postback.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top