Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET ImageButton单击事件_C#_Asp.net_Imagebutton - Fatal编程技术网

C# ASP.NET ImageButton单击事件

C# ASP.NET ImageButton单击事件,c#,asp.net,imagebutton,C#,Asp.net,Imagebutton,我有一个动态ImageButton,我希望它在单击时触发一个方法。我有下面的代码,不幸的是它不工作 ImageButton imb = new ImageButton(); imb.Attributes.Add("runat", "server"); imb.Click += new ImageClickEventHandler(ImageButton1_Click); imb.ID = "ID"; imb.ImageUrl = "link to

我有一个动态ImageButton,我希望它在单击时触发一个方法。我有下面的代码,不幸的是它不工作

ImageButton imb = new ImageButton();
imb.Attributes.Add("runat", "server");
        imb.Click += new ImageClickEventHandler(ImageButton1_Click);
        imb.ID = "ID";
        imb.ImageUrl = "link to image";
Panel1.Controls.Add(imb);

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    //it should go here
}

您必须将ImageButton添加到合适的容器中

e、 g:


您可以在上找到有用的提示。

向页面添加动态控件是一件棘手的事情。不幸的是,您不能仅仅声明一个派生类型为
WebControl
的对象并期望它工作

在ASP.NET WebForms中,有一个称为的概念。这是一个广泛的问题,但我的观点是,要将动态控件插入到页面中,您必须遵守一个特定的顺序。下面是一个实际例子

从类级别的动态控件声明开始

protected ImageButton imb = null;
然后在页面初始化过程中对其进行初始化。一种可能性是处理事件


你可以走了。

你拼写的
runat
错了。另外,OnClientClick用于javascript,请将其删除。有什么原因不能将控件放在页面上吗?修复了“runat”并删除了OnClientClick。该控件已添加到ASP面板,但仍不起作用。请使用当前代码更新您的问题。问题已使用当前代码更新。是的,它位于ASP面板中。面板1.控件。添加(imb);
protected ImageButton imb = null;
protected void Page_PreInit(object sender, EventArgs e)
{
    imb = new ImageButton()
    {
        ID = "ID",
        ImageUrl = "link to image"
    };

    imb.Click += Imb_Click;

    Panel1.Controls.Add(imb);

}

private void Imb_Click(object sender, ImageClickEventArgs e)
{
    // Do your stuff
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Set initial properties as appropriate. E.g.
        imb.AlternateText = "...";
    }
}