Friday, October 14, 2011

How to add own event handler in C#



The following code block allows the user creates textbox controls dynamically. However, on each creation I'd like to add a delete button to delete the speficied textbox. I know I can do this by adding a button control when the textbox is created and assign an event to the button in question. However, such act will result in unconvinient situations such as when you remove the textbox sometimes it will remove the last textbox and sometimes it will perform successfully. My question is how can I add a button near each textbox created to let the user remove the created control while preserving all the other dynamic controls?

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


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

No comments :

Post a Comment