![](/img/trans.png)
[英]ASP.net Linkbutton with onclick event in codebehind not working
[英]dynamic LinkButton OnClick event not working on ASP.Net
我想為圖像創建動態LinkButton, <img>
標簽不能動態工作,所以我將LinkButton與圖像一起使用。
我不想為LinkButton提供ID,因為我想動態生成更多LinkButton。 我在Default.aspx中使用以下代碼
<%@ Page Language="C#"%>
<!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>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(@"<asp:LinkButton runat=""server"" OnClick=""btn_click""><img src=""close-icon (1).png"" /></asp:LinkButton>");
}
public void btn_click(object sender, EventArgs e)
{
Response.Write("HELLO");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
我也嘗試在Default.aspx.cs文件中編寫標記代碼,但不起作用。
它向我顯示以下錯誤。
錯誤1'ASP.default_aspx'不包含'img_Click'的定義,並且找不到擴展方法'img_Click'接受類型為'ASP.default_aspx'的第一個參數(您是否缺少using指令或程序集引用?)
請幫我解決這個問題。
我找到了答案,答案在下面
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>
您的方法有誤,您的第一個Response.Write(“ ...”)而不是Response.Write(“
閱讀此文章以動態使用ASP.NET中的控件。
http://msdn.microsoft.com/en-us/library/kyt0fzt1%28v=vs.100%29.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.