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
codingitupagainAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.