[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 920
  • Last Modified:

Datatable viewstate lost on aspx page when clicking a button on a usercontrol on the aspx page

Hi All,

I've got the following code: -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace Testing.Event_Delegate
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebUserControl2 QT2;
        WebUserControl3 QT3;
        DataTable dtQuestionSet;

        protected void Page_Init(object sender, EventArgs e)
        {
            dtQuestionSet = (DataTable)ViewState["DataTableW"];
        }

        protected void Page_Load(object sender, EventArgs e)
        {           
            if (IsPostBack == false)
            {
                Session["Counter"] = 0;
                Session["QuestionCount"] = 0;
                Session["CompletedInsp"] = false;
            }

            //check to see if the inspection process is complete and display pass\fail and log. Else carry on.
            if (Convert.ToBoolean(Session["CompletedInsp"]) == true)
            {
                //Response.Write("Failed");
                ModalPopupExtender2.Show(); 
                return;
            }

                    // all controls need to be rendered every page postback otherwise the rest of the code loses scope.
                    QT2 = (WebUserControl2)this.LoadControl("WebUserControl2.ascx");
                    UC2BtnClickEvent.MyEvent2 += new UC2BtnClickEvent.OnMyEvent2(ChecKResult);
                    QT3 = (WebUserControl3)this.LoadControl("WebUserControl3.ascx");
                    UC2BtnClickEvent.MyEvent3 += new UC2BtnClickEvent.OnMyEvent3(ChecKResult);
                    PlaceHolder2.Controls.Add(QT2);
                    PlaceHolder2.Controls.Add(QT3);

                    QT2.Visible = false;
                    QT3.Visible = false;

                    if (IsPostBack == false)
                    {
                        dtQuestionSet = new DataTable();
                        MakeDataTabledtQuestionSet();
                    }
                    else
                    {
                        dtQuestionSet = (DataTable)ViewState["DataTableW"];
                    }
                    ViewState["DataTableW"] = dtQuestionSet;
        }

        void ChecKResult(object sender, EventArgs e, string strTextBox, string strMyDescription)
        {
            Label1.Text = "You Answered: - " + strMyDescription;

            Session["Counter"] = Convert.ToInt32(Session["Counter"]) + 1;

            if (Convert.ToInt32(Session["Counter"]) > Convert.ToInt32(Session["QuestionCount"]))
            {
                Session["CompletedInsp"] = true;
            }
            else
            {
                //carry on with inspection
                dtQuestionSet = (DataTable)ViewState["DataTableW"];
                RunInspection();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("WebForm1.aspx");
        }

        protected void cmdStartInspection_Click(object sender, EventArgs e)
        {
            Session["Counter"] = 0;
            GetQuestions();
        }

        protected void GetQuestions()
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PromptedInspConnectionString"].ConnectionString);
            conn.Open();

            SqlCommand cmd = new SqlCommand("test.GetQuestions", conn);
            SqlDataReader dr = null;
            cmd.CommandType = CommandType.StoredProcedure;
            //cmd.Parameters.Add(new SqlParameter("@Block1", cmbBlock1.Text));

            dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                DataRow drQuestions = dtQuestionSet.NewRow();
                drQuestions["QuestionText"] = dr[1].ToString();
                drQuestions["ExpectedResponse"] = dr[2].ToString();
                drQuestions["QuestionType"] = dr[3].ToString();
                dtQuestionSet.Rows.Add(drQuestions);
            }
               ViewState["DataTableW"] = dtQuestionSet;
               Session["QuestionCount"] = dtQuestionSet.Rows.Count;

            conn.Close();

            RunInspection();
        }

        protected void RunInspection()
        
        {
            switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
            {
                case "1":
                    QT2.QuestionText = dtQuestionSet.Rows[0][0].ToString();//"I'm asking a question 1";
                    QT2.Visible = true;
                    break;
                case "2":

                    QT3.QuestionText = dtQuestionSet.Rows[0][0].ToString();//"I'm asking a question 2";
                    QT3.Visible = true;
                    break;
            }
        }

        private void MakeDataTabledtQuestionSet()
        {
            dtQuestionSet.Columns.Add("QuestionText");
            dtQuestionSet.Columns.Add("ExpectedResponse");
            dtQuestionSet.Columns.Add("QuestionType");

        }

    }
}

Open in new window


when I click a button within the usercontrol "QT2" or "QT3" it posts back and then returns to the procedure "RunInspection". I then get the error: -

There is no row at position 1.

On Line : -

switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())

Despite me setting the datatable dtQuestionSet to the viewstate on postback.

What am I doing wrong please?

Best Regards
Lee
0
codingitupagain
Asked:
codingitupagain
1 Solution
 
Luis PérezSoftware Architect in .NetCommented:
Mmmm... I've lost reading your code, but anyway you can try to use a Session variable to store your datatable instead ViewState. Regarding the source of the problem (where are you losing the ViewState), the Session variable will be persistent.

Hope that helps.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now