【问题标题】:How can i catch onclick event of Dynamically loaded control?如何捕捉动态加载控件的 onclick 事件?
【发布时间】:2011-08-16 16:48:57
【问题描述】:

我有一个下拉列表(在页面上),其中包含 OnSelectedIndexChange 事件,每次动态加载不同的控件(ascx)(使用 LoadControl 命令) - 进入页面。

每个控件都有一个 Button(runat=server) 和 TextBox(runat=server)。

当我点击按钮时 - 我无法进入 Onclick 功能。

如何进入 Ascx 的 OnClick 功能?

我知道每个 SelectedIndexChange 都会进行回发 - 所以我知道我必须在视图状态中保存一些内容。但我不知道如何保存它,然后在 TexstBox 上获取值。 (每个 ascx 的)

【问题讨论】:

    标签: c# asp.net user-controls


    【解决方案1】:

    您需要向用户控件添加一个事件处理程序,如下所示:

    public event EventHandler ButtonClick;
    

    并且在按钮的点击事件中:

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (this.ButtonClick != null)
            this.ButtonClick(this, e);
    }
    

    然后,从页面中,你可以像这样得到点击事件:

    <UC:MyUserControl ID="UserControl1" runat="server" OnButtonClick="UserControl1_ButtonClick" ... />
    
    protected void UserControl1_ButtonClick(object sender, EventArgs e)
    {
       //Handle the click event here
    }
    

    如果您要动态加载控件,则需要确保控件在回发后重新水化,并通过代码分配事件处理程序来模拟上面的代码:

    MyUserControl ctrl = (MyUserControl)this.LoadControl("...");
    ctrl.ButtonClick += new EventHandler(UserControl1_ButtonClick);
    

    【讨论】:

    • 我需要在回帖中重新创建它,但还要获得它的值。一些朋友告诉我它的“控制状态”......???
    • 如果您在重新创建控件时为其分配相同的 ID,则应为您重新填充这些值。
    • @James:删除了我的。这是一个更完整的答案
    • 我相信,如果您在 OnPreInit 或 OnPreLoad 中重新水化控件,您将能够获得 OnClick。页面回发并重新生成控件后,应触发按钮单击事件。
    • 您在 OnPreInit 事件中重新创建它们,但这些值由控件 ID 存储。当您重新创建控件并为其分配 ID 时,与该 ID 对应的值将重新加载到控件中。
    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多