【问题标题】:Event not working with ParseControl method事件不适用于 ParseControl 方法
【发布时间】:2012-10-29 06:54:18
【问题描述】:

我想在没有图像按钮 ID 的情况下在网站上添加动态图像按钮,所以我使用 ASP 标签通过 ParseControl 方法生成动态控件,它正在工作,但单击图像按钮时不会触发事件

Default.aspx.cs 代码

        protected void Page_Load(object sender, EventArgs e)
        {
            string str = @"<asp:ImageButton runat=server ImageUrl=""~/close-icon (1).png"" OnClick=""click"" />";
            Control c = Page.ParseControl(str);
            form1.Controls.Add(c);
        }


        protected void click(object sender, ImageClickEventArgs e)
        {
            Response.Write("Image Clicl");
        }

Default.aspx 代码

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

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

请通过在解决方案中提供代码来帮助我解决我的问题。

【问题讨论】:

    标签: asp.net event-handling dynamic-controls


    【解决方案1】:

    我找到了答案,答案在下面

    Default.aspx.cs 代码

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class dynamicimage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string str = @"<asp:ImageButton ID=""dynoimage"" ImageUrl=""~/images/about01.jpg"" runat=""server"" oncommand=""clickme"" commandname=""btn"" />";
            Control c = ParseControl(str);
            form1.Controls.Add(c);
            ((ImageButton)Page.FindControl("dynoimage")).Command += new CommandEventHandler(clickme);
        }
    
        protected void clickme(object sender,CommandEventArgs e)
        {
            Response.Write("Image clicked");
            Label1.Text = "Image clicked";
        }
    }
    

    这里是 Default.aspx 页面:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="dynamicimage.aspx.cs" Inherits="dynamicimage" %>
    
    <!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>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
    
        </div>
        <p>
            <asp:Label ID="Label1" runat="server" Text="before click"></asp:Label>
        </p>
        </form>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-10
      • 2016-04-01
      • 2017-11-13
      • 1970-01-01
      相关资源
      最近更新 更多