locked
How to add own event handler in C# RRS feed

  • Question

  • User-1773939321 posted

      I found this article very useful while adding control in dynamically.

     http://www.codeproject.com/KB/user-controls/DynamicUC.aspx

    But when converting VB to C# I am facing problem in the event Handler.

     

    //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;

                DynamicUserControl.RemoveUserControl += new EventHandler(RemoveUserControl);

     

     

    void RemoveUserControl(object sender, EventArgs e)

        {

            //This handles delete event fired from the user control

     

            //Get the user control that fired this event, and remove it

            Admin_AddPhoto DynamicUserControl = sender.parent;

            ph1.Controls.Remove(sender.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 + "|";// ERROR: Unknown assignment operator ConcatString ;

     

            //Also, now that we've removed a user control decrement the count of total user controls on the page

            ltlCount.Text = Convert.ToString((Convert.ToInt16(ltlCount.Text) - 1));

            throw new Exception("The method or operation is not implemented.");

           

        }

     

    But when I call the “sender.Parent” here I am getting error

     

    Error      1              'object' does not contain a definition for 'parent'           

     

    How to remove the error. ? ???????

     

     

    Friday, June 20, 2008 1:54 AM

Answers

  • User-1228306975 posted

    ----- default page ----

    using System;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Text;

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AddAndRemoveDynamicControls();
        }

        private void AddAndRemoveDynamicControls()
        {
            Control c = new Control();
            c = GetPostBackControl(Page);
            if (c != null)
            {
                if (c.ID.ToString() == "btnAdd")
                {
                    ltlCount.Text = (Convert.ToInt16(ltlCount.Text) + 1).ToString();
                }
            }
            ph1.Controls.Clear();
            int ControlID = 0;

            for (int i = 0; i <= (Convert.ToInt16(ltlCount.Text) - 1); i++)
            {
                WebUserControl DynamicUserControl = LoadControl("WebUserControl.ascx") as WebUserControl;
                while (InDeletedList("uc" + ControlID) == true)
                {
                    ControlID += 1;
                }
                DynamicUserControl.ID = "uc" + ControlID;
                DynamicUserControl.RemoveUserControl += new EventHandler(HandleRemoveUserControl);
                ph1.Controls.Add(DynamicUserControl);
                ControlID += 1;
            }
        }

        public void HandleRemoveUserControl(object sender, EventArgs e)
        {
            Button but = sender as Button;
            WebUserControl DynamicUserControl = (WebUserControl)but.Parent;
            ph1.Controls.Remove(DynamicUserControl);
            ltlRemoved.Text += DynamicUserControl.ID + "|";
            ltlCount.Text = (Convert.ToInt16(ltlCount.Text) - 1).ToString();
        }

        private bool InDeletedList(string ControlID)
        {
            string[] DeletedList = ltlRemoved.Text.Split(new string[] { "|" }, StringSplitOptions.None);
            for (int i = 0; i < DeletedList.GetLength(0) - 1; i++)
            {
                if (ControlID.ToLower() == DeletedList[i].ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        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;
        }

        protected void btnDisplayValues_Click(object sender, EventArgs e)
        {
            ltlValues.Text = "";
            foreach (Control c in ph1.Controls)
            {

                if (c.GetType().Name.ToString() == "webusercontrol_ascx")
                {
                    UserControl uc = (UserControl)c;
                    TextBox tbx1 = (TextBox)uc.FindControl("tbx1");
                    DropDownList ddl1 = (DropDownList)uc.FindControl("ddl1");
                    CheckBoxList cbx1 = (CheckBoxList)uc.FindControl("cbx1");

                    StringBuilder sb = new StringBuilder();
                    sb.Append("Textbox value: " + tbx1.Text + "<br />");
                    sb.Append("Dropdown value: " + ddl1.SelectedValue + "<br />");
                    sb.AppendLine("Checkbox values: ");

                    foreach (ListItem li in cbx1.Items)
                    {
                        if (li.Selected == true)
                        {
                            sb.Append(li.Value + "<br />");
                        }
                    }

                    sb.Append("<hr />");

                    ltlValues.Text += sb.ToString();
                }
            }
        }
    }

     

    ------ WebUserControl.ascx.cs -------

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;

    public partial class WebUserControl : System.Web.UI.UserControl
    {
        public event EventHandler RemoveUserControl;

        protected void btnRemove_Click(object sender, EventArgs e)
        {
            if (RemoveUserControl != null)
            {
                RemoveUserControl(sender, e);
            }
        }
    }
     

     

    ------- WebUserControl.ascx ------

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>

        <table>
            <tr>
                <td>Textbox Example:</td>
                <td>
                    <asp:TextBox ID="tbx1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>Dropdown Example:</td>
                <td>
                    <asp:DropDownList ID="ddl1" runat="server">
                        <asp:ListItem Text="Dropdown 1" />
                        <asp:ListItem Text="Dropdown 2" />
                        <asp:ListItem Text="Dropdown 3" />
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>Checkbox Example:</td>
                <td>
                    <asp:CheckBoxList ID="cbx1" runat="server">
                        <asp:ListItem Text="Checkbox 1" />
                        <asp:ListItem Text="Checkbox 2" />
                        <asp:ListItem Text="Checkbox 3" />
                    </asp:CheckBoxList>
                </td>
            </tr>
        </table>
        <asp:Button ID="btnRemove" runat="server" Text="Remove" OnClick="btnRemove_Click" />

     ------ Default.aspx -------

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Dynamic User Control Demo</title>
        <style type="text/css">
            div.demo

            {
               width:300px;
               float:left;
               padding:20px;
               margin: 10px;
               border: solid black 1px;        
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
           
            <asp:UpdatePanel ID="up1" runat="server">
                <ContentTemplate>
                    <div class="demo">
                        <asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>
                        <asp:Button ID="btnAdd" runat="server" Text="Add" />
                    </div>
                    <div class="demo">
                        <asp:Literal ID="ltlValues" runat="server"></asp:Literal>
                        <asp:Button ID="btnDisplayValues" runat="server" Text="Display Values"
                            onclick="btnDisplayValues_Click" />
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
           
            <asp:Literal ID="ltlCount" runat="server" Text="0" Visible="false"></asp:Literal>
            <asp:Literal ID="ltlRemoved" runat="server" Visible="false"></asp:Literal>
        </div>
        </form>
    </body>
    </html>
     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, October 18, 2008 3:46 PM

All replies

  • User-2058416358 posted
    Hi place ((Control)sender).Parent in place of sender.parent and try.
    Friday, June 20, 2008 2:52 AM
  • User-1824631895 posted

    sender is an object variable and obviously, object do not possess a Parent property. try casting sender to the appropriate type. and calling the parent property on that type

    e.g

    Control ctrl = (Control)sender;

    Admin_AddPhoto DynamicUserControl = bttn.Parent;

     

    thats it.


     

    Friday, June 20, 2008 9:18 AM
  • User251781917 posted

    You need to cast sender to the appropriate class type. For example:

     
    1    void EventHandlerMethod(object sender, EventArgs e) 
    2    {
    3        Button button = sender as Button;
    4        Admin_AddPhoto dynamicUserControl = button.Parent;
    5    
    6        // put remaining functionality here
    7    }
    
     
    I hope this helps. 
    Friday, June 20, 2008 7:56 PM
  • User-1773939321 posted

     Thanks aggiekevin,

    Have you read the link of CodeProject which i sent to to if you try it it's working but it is written VB. How can i convert and use in C#.........................?????????????

    Friday, June 20, 2008 11:41 PM
  • User-1228306975 posted

    ----- default page ----

    using System;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Text;

    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            AddAndRemoveDynamicControls();
        }

        private void AddAndRemoveDynamicControls()
        {
            Control c = new Control();
            c = GetPostBackControl(Page);
            if (c != null)
            {
                if (c.ID.ToString() == "btnAdd")
                {
                    ltlCount.Text = (Convert.ToInt16(ltlCount.Text) + 1).ToString();
                }
            }
            ph1.Controls.Clear();
            int ControlID = 0;

            for (int i = 0; i <= (Convert.ToInt16(ltlCount.Text) - 1); i++)
            {
                WebUserControl DynamicUserControl = LoadControl("WebUserControl.ascx") as WebUserControl;
                while (InDeletedList("uc" + ControlID) == true)
                {
                    ControlID += 1;
                }
                DynamicUserControl.ID = "uc" + ControlID;
                DynamicUserControl.RemoveUserControl += new EventHandler(HandleRemoveUserControl);
                ph1.Controls.Add(DynamicUserControl);
                ControlID += 1;
            }
        }

        public void HandleRemoveUserControl(object sender, EventArgs e)
        {
            Button but = sender as Button;
            WebUserControl DynamicUserControl = (WebUserControl)but.Parent;
            ph1.Controls.Remove(DynamicUserControl);
            ltlRemoved.Text += DynamicUserControl.ID + "|";
            ltlCount.Text = (Convert.ToInt16(ltlCount.Text) - 1).ToString();
        }

        private bool InDeletedList(string ControlID)
        {
            string[] DeletedList = ltlRemoved.Text.Split(new string[] { "|" }, StringSplitOptions.None);
            for (int i = 0; i < DeletedList.GetLength(0) - 1; i++)
            {
                if (ControlID.ToLower() == DeletedList[i].ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        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;
        }

        protected void btnDisplayValues_Click(object sender, EventArgs e)
        {
            ltlValues.Text = "";
            foreach (Control c in ph1.Controls)
            {

                if (c.GetType().Name.ToString() == "webusercontrol_ascx")
                {
                    UserControl uc = (UserControl)c;
                    TextBox tbx1 = (TextBox)uc.FindControl("tbx1");
                    DropDownList ddl1 = (DropDownList)uc.FindControl("ddl1");
                    CheckBoxList cbx1 = (CheckBoxList)uc.FindControl("cbx1");

                    StringBuilder sb = new StringBuilder();
                    sb.Append("Textbox value: " + tbx1.Text + "<br />");
                    sb.Append("Dropdown value: " + ddl1.SelectedValue + "<br />");
                    sb.AppendLine("Checkbox values: ");

                    foreach (ListItem li in cbx1.Items)
                    {
                        if (li.Selected == true)
                        {
                            sb.Append(li.Value + "<br />");
                        }
                    }

                    sb.Append("<hr />");

                    ltlValues.Text += sb.ToString();
                }
            }
        }
    }

     

    ------ WebUserControl.ascx.cs -------

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;

    public partial class WebUserControl : System.Web.UI.UserControl
    {
        public event EventHandler RemoveUserControl;

        protected void btnRemove_Click(object sender, EventArgs e)
        {
            if (RemoveUserControl != null)
            {
                RemoveUserControl(sender, e);
            }
        }
    }
     

     

    ------- WebUserControl.ascx ------

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>

        <table>
            <tr>
                <td>Textbox Example:</td>
                <td>
                    <asp:TextBox ID="tbx1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>Dropdown Example:</td>
                <td>
                    <asp:DropDownList ID="ddl1" runat="server">
                        <asp:ListItem Text="Dropdown 1" />
                        <asp:ListItem Text="Dropdown 2" />
                        <asp:ListItem Text="Dropdown 3" />
                    </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>Checkbox Example:</td>
                <td>
                    <asp:CheckBoxList ID="cbx1" runat="server">
                        <asp:ListItem Text="Checkbox 1" />
                        <asp:ListItem Text="Checkbox 2" />
                        <asp:ListItem Text="Checkbox 3" />
                    </asp:CheckBoxList>
                </td>
            </tr>
        </table>
        <asp:Button ID="btnRemove" runat="server" Text="Remove" OnClick="btnRemove_Click" />

     ------ Default.aspx -------

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

    <%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Dynamic User Control Demo</title>
        <style type="text/css">
            div.demo

            {
               width:300px;
               float:left;
               padding:20px;
               margin: 10px;
               border: solid black 1px;        
            }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
           
            <asp:UpdatePanel ID="up1" runat="server">
                <ContentTemplate>
                    <div class="demo">
                        <asp:PlaceHolder ID="ph1" runat="server"></asp:PlaceHolder>
                        <asp:Button ID="btnAdd" runat="server" Text="Add" />
                    </div>
                    <div class="demo">
                        <asp:Literal ID="ltlValues" runat="server"></asp:Literal>
                        <asp:Button ID="btnDisplayValues" runat="server" Text="Display Values"
                            onclick="btnDisplayValues_Click" />
                    </div>
                </ContentTemplate>
            </asp:UpdatePanel>
           
            <asp:Literal ID="ltlCount" runat="server" Text="0" Visible="false"></asp:Literal>
            <asp:Literal ID="ltlRemoved" runat="server" Visible="false"></asp:Literal>
        </div>
        </form>
    </body>
    </html>
     

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, October 18, 2008 3:46 PM
  • User251781917 posted

     Thanks aggiekevin,

    Have you read the link of CodeProject which i sent to to if you try it it's working but it is written VB. How can i convert and use in C#.........................?????????????

     

     

    Hi Hamza,

    If you still need to convert code from VB to C# (or vice versa), I highly recommend trying Telerik's Code Converter, which allows you to easily convert code between the two languages. Check it out at this link.

    I hope that helps.

    Monday, October 20, 2008 3:06 PM
  • User-1940854371 posted

    Hi here i post easiest way to add and remove web user control dynamically


    webuser control ascx page :

    AddTier.ascx

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="AddTier.ascx.cs" Inherits="AddTier" %>
    <tr>
        <td>
            <asp:Label runat="server" ID="lblTier"></asp:Label>
        </td>
        <td>
            <asp:DropDownList runat="server" ID="drp">
                <asp:ListItem Selected="True">$</asp:ListItem>
                <asp:ListItem Value="%"></asp:ListItem>
            </asp:DropDownList>
        </td>
        <td>
            <asp:TextBox runat="server" ID="txt"></asp:TextBox>
            <asp:RequiredFieldValidator runat="server" ID="reqtxt" ControlToValidate="txt" ErrorMessage="*"></asp:RequiredFieldValidator>
        </td>
    </tr>


    page for dynamically add this control :

    TestConrol.aspx

                <asp:Button runat="server" ID="btnSaleTier" Text="Add Tier" OnClick="btnSaleTier_Click" />
                <asp:Button runat="server" ID="btnSaleRemove" Text="Remove Last Tier" OnClick="btnSaleRemove_Click" />
                <table>
                    <asp:Panel runat="server" ID="pnlAddSaleTier">
                    </asp:Panel>
                </table>

    TestControl.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
        {

      int num = 0;
            if (ViewState["Counter"] != null)
            {
                num = (int)ViewState["Counter"];
            }
            else
            {
                ViewState["Counter"] = 0;
            }
            for (int j = 0; j < num; j++)
            {
                Control cl = LoadControl("~/AddTier.ascx");

                cl.ID = "c" + j;
                if (pnlAddSaleTier.FindControl(cl.ID) != null)
                {

                }
                else
                {
                    pnlAddSaleTier.Controls.Add(cl);
                }
            }
            if (ViewState["Remove"] == "1")
            {
                pnlAddSaleTier.Controls.RemoveAt(Convert.ToInt32(ViewState["Counter"]));
            }

    }

        protected void btnSaleTier_Click(object sender, EventArgs e)
        {
            ViewState["Counter"] = (int)ViewState["Counter"] + 1;
            Page_Load(Page, new EventArgs());
        }

     protected void btnSaleRemove_Click(object sender, EventArgs e)
        {
         
            ViewState["Remove"] = "1";
            Page_Load(Page, new EventArgs());
            ViewState["Remove"] = "0";
            ViewState["Counter"] = (int)ViewState["Counter"] - 1;
        }


    Hope this will help you.

    http://khushi20.blogspot.com/

    http://jayeshmodasa.wordpress.com/

    Best Regards,

    Jayesh Patel


    Thursday, January 13, 2011 12:44 AM
  • User1239874837 posted

    Thanks very much!

    This is what I want.

    Sunday, March 27, 2011 11:19 AM
  • User346727691 posted

    i try this last easy example but give me debug said , 

     

    

    The name 'pnlAddSaleTier' does not exist in the current context
    Saturday, May 14, 2011 11:46 AM
  • User346727691 posted

    wangbang , could you please help me , wich one you have been using of this 2 examples , because the first one is too long i think and the second make the same work but with less code and effort , right ?

    send me back please

    Saturday, May 14, 2011 11:47 AM
  • User1590754065 posted

    HI All! both the above codes work fine. But how about having a file upload control in the User control..??

    Wednesday, November 30, 2011 3:37 PM