c# - Asp.NET 服务器控件回发

标签 c# asp.net events user-controls postback

我有一个要创建的控件。这是我要完成的任务的一个简单示例。

我希望控件包含一个按钮。

Button b = new Button();
b.Text = "Test";
b.Click += new EventHandler(b_Click);

this.Controls.Add(b);

现在,控件呈现良好,按钮显示在页面上。我遇到的问题的核心是 b_Click 事件处理程序从未被触发。

protected void b_Click(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

如有任何帮助,我们将不胜感激。纯粹出于自私的原因,我不想在这里使用用户控件,而是想将它完全封装在一个 DLL 中。

提前致谢。

编辑**

namespace ClassLibrary1
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
    public class WebCustomControl1 : WebControl
    {

        protected override void CreateChildControls()
        {
            Button b = new Button();
                    b.ID = "button";
            b.Text = "Click Me";
            b.Click += new EventHandler(b_Click);

            this.Controls.Add(b);

            base.CreateChildControls();
        }

        protected void b_Click(object sender, EventArgs e)
        {
            this.Controls.Add(new LiteralControl("<p>Click!</p>"));
        }

    }
}

所以根据我已经尝试过的评论。最简单的例子,还是不行。我从根本上缺少什么吗?

最佳答案

public class WebCustomControl1 : WebControl

需要

public class WebCustomControl1 : WebControl, INamingContainer

就是这样。这就是使此回发问题正常工作所需的全部内容。

关于c# - Asp.NET 服务器控件回发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1088932/

相关文章:

c# - 此操作会创建结构不正确的文档

javascript - jquery fancybox 触发点击只工作一次

c# - 使用弹性数据库客户端库、EF 和 Identity 时找不到 DbContext

c# - 我可以在 CreateAssetMenu 中设置子文件夹的排序顺序吗?

c# - Int32 的值太大或太小 - Facebook 和 dotnetopenauth

c# - 如何使用表单例份验证实现对多个文件夹的重定向

c# - 使用 C# 中的子查询 Access 数据库 INSERT

JavaScript 无法检测鼠标滚轮事件

java - 如何通过执行另一个类中的操作来更改一个类中图形的颜色?

c# - 命令按钮在 c# 客户端应用程序中不显示下划线快捷方式