简体   繁体   中英

Event not firing with dynamically placed user control asp.net c#

I'm trying to create a webpage that displays dynamically placed WebUserControls depending on a question type that is returned from and SQL server. When you press a button on the usercontrols it checks the result from the usercontrol using the procedure “CheckResult”. For some reason when you click on the buttons within the usercontrols ("cmdProcess") the Event “CheckResult” does not fire. What am I doing wrong please?

The User control code is: -

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Testing.Event_Delegate
{
    public partial class WebUserControl2 : System.Web.UI.UserControl
    {

        // Delegate declaration
        public delegate void PhotoUploaded(string strFilename, String FailureMessage, string strFabricationNo, string strPartNo, string strBatchNo, string strPartSN, string strSTK_SerialNo, string strSTK_PartNo);

        // Event declaration
        public event PhotoUploaded Resultresponse;

        string questionAsked;

        public string QuestionText
        {
            set { questionAsked = value; }
            get { return questionAsked; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = QuestionText;
            TextBox1.Focus();
        }

        protected void cmdProcess_Click(object sender, EventArgs e)
        {
            if (Resultresponse != null)
            {
                Resultresponse("Passed", "", "", "", "", "", "", "");
            }
            TextBox1.Text = "";

        }


    }
}

And the main ASPX page that the usercontrols are placed on is: -

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_Load(object sender, EventArgs e)
        {
            // all controls need to be rendered every page postback otherwise the rest of the code loses scope.
            QT2 = (WebUserControl2)this.LoadControl("WebUserControl2.ascx");            
            QT3 = (WebUserControl3)this.LoadControl("WebUserControl3.ascx");

            if (IsPostBack == false)
            {
                Session["Counter"] = 0;
                Session["QuestionCount"] = 0;
                Session["CompletedInsp"] = false;
                Session["RunInsp"] = false;
                dtQuestionSet = new DataTable();
                MakeDataTabledtQuestionSet();
            }
            else
            {               
                dtQuestionSet = (DataTable)Session["DataTableW"];
                //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;
                }
            }
            Session["DataTableW"] = dtQuestionSet;
        }

        void CheckResult(string Result, string FailureMessage, string FabricationNo, string PartNo, string BatchNo, string PartSN, string STK_SerialNo, string STK_PartNo)
        {
            Label1.Text = "You Answered: - " + Result;

            if ((Convert.ToInt32(Session["Counter"]))>= Convert.ToInt32(Session["QuestionCount"]))
            {
                Session["CompletedInsp"] = true;
                Session["RunInsp"] = false;
            }
            else
            {
                dtQuestionSet = (DataTable)Session["DataTableW"];
            }

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

            //If the inspection hasn't been completed carry on and ask next question.
            if (Convert.ToBoolean(Session["RunInsp"]) == true)
            {
                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()
        {

            dtQuestionSet.Clear();
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PromptedInspConnectionString"].ConnectionString);
            conn.Open();

            SqlCommand cmd = new SqlCommand("test.GetQuestions", conn);
            SqlDataReader dr = null;
            cmd.CommandType = CommandType.StoredProcedure;

            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);
            }
            Session["DataTableW"] = dtQuestionSet;
            Session["QuestionCount"] = dtQuestionSet.Rows.Count;

            conn.Close();

            RunInspection();
            Session["RunInsp"] = true;
        }

        protected void RunInspection()
        {

            //Populate the user controls
            switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
            {                              
                case "1":            
                    QT2.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
                    QT2.Resultresponse += new WebUserControl2.PhotoUploaded(CheckResult);
                    break;
                case "2":
                    QT3.QuestionText = dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][0].ToString();
                    QT3.Resultresponse += new WebUserControl3.PhotoUploaded(CheckResult);
                    break;
            }

            //Add the usercontrols to the form 
            PlaceHolder2.Controls.Add(QT2);
            PlaceHolder2.Controls.Add(QT3);

            //Need to set the visability of the usercontrol so it only shows the usercontrol that is displaying the question
            QT2.Visible = false;
            QT3.Visible = false;

            switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
            {
                case "1":
                    QT2.Visible = true;
                    break;
                case "2":
                    QT3.Visible = true;
                    break;
            }
        }

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

    }
}

Try initializing the controls in OnPreInit rather than load. Controls binding is done in OnPreInit.

See the page lifecyle events MSDN Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM