问题将事件绑定到动态创建的控件

时间:2022-10-22 07:34:26

I have a page with some drop down controls, I cant bind events to thos dynamically created controls here is my code:

我有一个带有一些下拉控件的页面,我无法将事件绑定到动态创建的控件这里是我的代码:

test21.aspx

test21.aspx

enter code here

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

<!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></title><script type="text/javascript">

        function BindEvents() {
            $(document).ready(function() {
                $(".tr-base").mouseover(function() {
                    $(this).toggleClass("trHover");
                }).mouseout(function() {
                    $(this).removeClass("trHover");
                });
         }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server" ></asp:ScriptManager>
    <asp:UpdatePanel runat="server" ID="UpdatePanel1">
    <ContentTemplate>

    <asp:Panel ID="pnlDropDownList1" runat="server">
        </asp:Panel>
           <script type="text/javascript">
               Sys.Application.add_load(BindEvents);
     </script>

    </ContentTemplate>

    </asp:UpdatePanel> 


    </div>

    </form>
</body>
</html>

and here is the aspx.cs

这是aspx.cs

enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class test21 : System.Web.UI.Page
{
    Panel pnlDropDownList;

   // protected void Page_PreInit(object sender, EventArgs e)
       protected override void OnInit(EventArgs e) 
    {


        //Create a Dynamic Panel
        pnlDropDownList = new Panel();
        pnlDropDownList.ID = "pnlDropDownList";
        pnlDropDownList.BorderWidth = 1;
        pnlDropDownList.Width = 300;
       // this.form1.Controls.Add(pnlDropDownList);


        //Create a LinkDynamic Button to Add TextBoxes
        LinkButton btnAddDdl = new LinkButton();
        btnAddDdl.ID = "btnAddDdl";
        btnAddDdl.Text = "Add DropDownList";
        btnAddDdl.Click += new System.EventHandler(btnAdd_Click);
     //   this.form1.Controls.Add(btnAddDdl);

        this.pnlDropDownList1.Controls.Add(pnlDropDownList);

        //Recreate Controls
        RecreateControls("ddlDynamic", "DropDownList");

        base.OnInit(e);
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        DropDownList sr =  (DropDownList)sender;

            int cnt = FindDropDownNumber("ddlDynamic");
            CreateDropDownList("ddlDynamic-" + Convert.ToString(cnt + 1));


    }

    private int FindDropDownNumber(string substr)
    {
        //الهدف من هذه الفنكشن هو معرفة الرقم الملحق باسم الدروب داون لست
        string reqstr = Request.Form.ToString();
        return ((reqstr.Length - reqstr.Replace(substr, "").Length)/ substr.Length);

    }

    private void CreateDropDownList(string ID)
    {

        DropDownList ddl = new DropDownList();

        ddl.ID = ID;
        ddl.Items.Add(new ListItem("--Select--", ""));
        ddl.Items.Add(new ListItem("One", "1"));
        ddl.Items.Add(new ListItem("Two", "2"));
        ddl.Items.Add(new ListItem("Three", "3"));
        ddl.AutoPostBack = true;
        ddl.SelectedIndexChanged += new EventHandler(OnSelectedIndexChanged);

        pnlDropDownList.Controls.Add(ddl);
        //ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert",
        //             "<script type = 'text/javascript'> alert('" + ID +
        //              " fired SelectedIndexChanged event');</script>");





        Literal lt = new Literal();
        lt.Text = "<br />";
        pnlDropDownList.Controls.Add(lt);
    }
    protected void OnSelectedIndexChanged(object sender, EventArgs e)
    {

        DropDownList ddl = (DropDownList)sender;
        string ID = ddl.ID;

        btnAdd_Click(sender, e);


        //Place the functionality here

    }
    private void RecreateControls(string ctrlPrefix, string ctrlType)
    {

        string[] ctrls = Request.Form.ToString().Split('&');

        int cnt = FindDropDownNumber(ctrlPrefix);

        if (cnt > 0)
        {

            for (int k = 1; k <= cnt; k++)
            {

                for (int i = 0; i < ctrls.Length; i++)
                {

                    if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString())

                        && !ctrls[i].Contains("EVENTTARGET"))
                    {

                        string ctrlID = ctrls[i].Split('=')[0];



                        if (ctrlType == "DropDownList")
                        {

                            CreateDropDownList(ctrlID);

                        }

                        break;

                    }

                }

            }

        }

    }



    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
        DropDownList ddlDynamicini = new DropDownList();
        ddlDynamicini.ID = "ddlDynamic-1";


        ddlDynamicini.Items.Add(new ListItem("--Select--", ""));
        ddlDynamicini.Items.Add(new ListItem("One", "1"));
        ddlDynamicini.Items.Add(new ListItem("Two", "2"));
        ddlDynamicini.Items.Add(new ListItem("Three", "3"));
        ddlDynamicini.AutoPostBack = true;
        ddlDynamicini.SelectedIndexChanged += new EventHandler(OnSelectedIndexChanged);
        pnlDropDownList.Controls.Add(ddlDynamicini);
        }
    }

}

Anay help please?? :(

Anay帮忙吗? :(

1 个解决方案

#1


1  

The ready() function is only called when the page initially loads. What you want is to attach the events after each Ajax request, so you want to use the live() function.

ready()函数仅在页面最初加载时调用。你想要的是在每个Ajax请求之后附加事件,因此你想使用live()函数。

Edit

编辑

I think you can remove the call to add_load, and the BindEvents function, and just do this:

我想你可以删除对add_load和BindEvents函数的调用,然后执行以下操作:

$(document).ready(function() {
    $(".tr-base").live("mouseover", function() {
        $(this).toggleClass("trHover");
    });
    $(".tr-base").live("mouseout", (function() {
        $(this).removeClass("trHover");
    });
}

This assumes, of course, that your newly-added elements will have the "tr-base" class, which I didn't see in your code sample.

当然,这假定您新添加的元素将具有“tr-base”类,我在您的代码示例中没有看到。

#1


1  

The ready() function is only called when the page initially loads. What you want is to attach the events after each Ajax request, so you want to use the live() function.

ready()函数仅在页面最初加载时调用。你想要的是在每个Ajax请求之后附加事件,因此你想使用live()函数。

Edit

编辑

I think you can remove the call to add_load, and the BindEvents function, and just do this:

我想你可以删除对add_load和BindEvents函数的调用,然后执行以下操作:

$(document).ready(function() {
    $(".tr-base").live("mouseover", function() {
        $(this).toggleClass("trHover");
    });
    $(".tr-base").live("mouseout", (function() {
        $(this).removeClass("trHover");
    });
}

This assumes, of course, that your newly-added elements will have the "tr-base" class, which I didn't see in your code sample.

当然,这假定您新添加的元素将具有“tr-base”类,我在您的代码示例中没有看到。