ASP.Net Sys.WebForms.PageRequestManagerServerErrorException: Unable to cast object of type 'control1_ascx' to type 'UserControl'

Last Reply one year ago By dharmendr

Posted one year ago

Dear All,

I'm using this link http://www.aspforums.net/Threads/101989/Dynamically-add-and-remove-TextBox-and-save-value-to-Database-with-UserControl-using-C-and-VBNet-in-ASPNet/

But im getting the error in This Line

UserControl DynamicUserControl = (UserControl)LoadControl("WebUserControl1.ascx");

Error: Sys.WebForms.PageRequestManagerServerErrorException: Unable to cast object of type 'ASP.webusercontrol1_ascx' to type 'StrategicKPI.UserControl' 

Usercontrol:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="StrategicKPI.WebUserControl1" %>
<link href="css/bootstrap.min.css" rel="stylesheet" />


    <table class="table table-bordered">
     <tr>
        <td colspan="4">
            Twice a year KPI Data Insertion
        </td>
    </tr>
    <tr>
        <td>
            Enter Year
        </td>
        <td>
           Select Quater
        </td>
        <td>
            Enter Year Value
        </td>
        <td></td>
    </tr>
    <tr>
        <td>
            <asp:TextBox ID="txt_year" runat="server"></asp:TextBox>

        </td>
        <td>
            <asp:DropDownList ID="dropdown_quater" runat="server">
                <asp:ListItem Value="0">Q1</asp:ListItem>
                <asp:ListItem Value="1">Q2</asp:ListItem>
            </asp:DropDownList>

        </td>
        <td>
            <asp:TextBox ID="txt_yearvalue" runat="server"></asp:TextBox>

        </td>
        <td>

             <asp:Button ID="btnRemove1" runat="server" Text="Remove" CssClass="btn btn-danger" OnClick="btnRemove1_Click"  />
        </td>
    </tr>

    
</table>

 

public partial class WebUserControl1 : System.Web.UI.UserControl
    {
        public event EventHandler RemoveUserControl1;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnRemove1_Click(object sender, EventArgs e)
        {
            RemoveUserControl1(sender, e);
        }
    }

Page:

<%@ Register Src="WebUserControl1.ascx" TagName="UserControl1" TagPrefix="uc2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

   <div>
        <asp:ScriptManager ID="sm1" runat="server" />
        <asp:UpdatePanel ID="up1" runat="server">
            <ContentTemplate>
                <div class="demo">
                    <table>
                        <tr>
                            <td>
                                <asp:PlaceHolder ID="ph1" runat="server" />
                                <br />
                                <asp:Button ID="btnAdd" runat="server" Text="Add" />
                            </td>
                        </tr>
                    </table>
                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
        <br />
        <asp:Button ID="btnInsert" runat="server" Text="Insert" OnClick="btnInsert_Click" />
        <asp:Literal ID="ltlCount" runat="server" Text="0" Visible="false" />
        <asp:Literal ID="ltlRemoved" runat="server" Visible="false" />
        <br />
        <br />
        <asp:GridView runat="server" ID="gvInsertedRecords" />
    </div>

</asp:Content>

 

    protected void Page_Load(object sender, System.EventArgs e)
    {
        AddAndRemoveDynamicControls();
    }
 
    private void AddAndRemoveDynamicControls()
    {
        //Determine which control fired the postback event. 
        Control c = GetPostBackControl(Page);
 
        if ((c != null))
        {
            //If the add button was clicked, increase the count to let the page know we want to display an additional user control
            if (c.ID.ToString() == "btnAdd")
            {
                ltlCount.Text = (Convert.ToInt16(ltlCount.Text) + 1).ToString();
            }
        }
 
        //Be sure everything in the placeholder control is cleared out
        ph1.Controls.Clear();
 
        int ControlID = 0;
 
        //Since these are dynamic user controls, re-add them every time the page loads.
        for (int i = 0; i <= (Convert.ToInt16(ltlCount.Text) - 1); i++)
        {
            UserControl DynamicUserControl = (UserControl)LoadControl("WebUserControl1.ascx");
 
            //If this particular control id has been deleted from the page, DO NOT use it again.  If we do, it will
            //pick up the viewstate data from the old item that had this control id, instead of generating
            //a completely new control.  Instead, increment the control id so we're guaranteed to get a "new"
            //control that doesn't have any lingering information in the viewstate.           
            while (InDeletedList("uc2" + ControlID) == true)
            {
                ControlID += 1;
            }
 
            //Note that if the item has not been deleted from the page, we DO want it to use the same control id
            //as it used before, so it will automatically maintain the viewstate information of the user control
            //for us.
            DynamicUserControl.ID = "uc2" + ControlID;
 
            //Add an event handler to this control to raise an event when the delete button is clicked
            //on the user control
            DynamicUserControl.RemoveUserControl += this.HandleRemoveUserControl;
 
            //Finally, add the user control to the panel
            ph1.Controls.Add(DynamicUserControl);
 
            //Increment the control id for the next round through the loop
            ControlID += 1;
        }
    }
 
    private bool InDeletedList(string ControlID)
    {
        //Determine if the passed in user control id has been stored in the list of controls that were previously deleted off the page
        string[] DeletedList = ltlRemoved.Text.Split('|');
        for (int i = 0; i <= DeletedList.GetLength(0) - 1; i++)
        {
            if (ControlID.ToLower() == DeletedList[i].ToLower())
            {
                return true;
            }
        }
        return false;
    }
 
    public void HandleRemoveUserControl(object sender, EventArgs e)
    {
        //This handles delete event fired from the user control
        Button remove = (sender as Button);
        //Get the user control that fired this event, and remove it
        UserControl DynamicUserControl = (UserControl)remove.Parent;
        ph1.Controls.Remove((UserControl)remove.Parent);
 
        //Keep a pipe delimited list of which user controls were removed.  This will increase the
        //viewstate size if the user keeps removing dynamic controls, but under normal use
        //this is such a small increase in size that it shouldn't be an issue.
        ltlRemoved.Text += DynamicUserControl.ID + "|";
 
        //Also, now that we've removed a user control decrement the count of total user controls on the page
        ltlCount.Text = (Convert.ToInt16(ltlCount.Text) - 1).ToString();
    }
 
    protected void btnAdd_Click(object sender, System.EventArgs e)
    {
        //Handled in page load
    }
 
    protected void btnInsert_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("StateId"), new DataColumn("State") });
        foreach (Control c in ph1.Controls)
        {
            //Find the specific user control that we added to this placeholder, and then get the selected values
            //for the dropdownlist, checkbox, and textbox and print them to the screen.
            if (c.GetType().Name.ToLower() == "usercontrol_ascx")
            {
                UserControl uc2 = (UserControl)c;
                TextBox tbState = uc2.FindControl("txtState") as TextBox;
                TextBox tbStateId = uc2.FindControl("txtStateId") as TextBox;
                if (!string.IsNullOrEmpty(tbStateId.Text.Trim()) && !string.IsNullOrEmpty(tbState.Text.Trim()))
                {
                    dt.Rows.Add(tbStateId.Text.Trim(), tbState.Text.Trim());
                    //Insert(tbStateId.Text.Trim(), tbState.Text.Trim());
                }
            }
        }
        gvInsertedRecords.DataSource = dt;
        gvInsertedRecords.DataBind();
    }
 
    private void Insert(string state, string id)
    {
        string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            string query = "INSERT INTO tblStates VALUES (@StateId, @State)";
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@StateId", id);
                cmd.Parameters.AddWithValue("@State", state);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
 
    //Find the control that caused the postback.
    public Control GetPostBackControl(Page page)
    {
        Control control = null;
 
        string ctrlname = page.Request.Params.Get("__EVENTTARGET");
        if ((ctrlname != null) & ctrlname != string.Empty)
        {
            control = page.FindControl(ctrlname);
        }
        else
        {
            foreach (string ctl in page.Request.Form)
            {
                Control c = page.FindControl(ctl);
                if (c is System.Web.UI.WebControls.Button)
                {
                    control = c;
                    break;
                }
            }
        }
        return control;
    }
}

Thanks in advance

You are viewing reply posted by: dharmendr one year ago.