[英]adding event handler to a dynamically created button
我已經在c#代碼隱藏中創建了一個按鈕,並嘗試向其添加事件偵聽器,但是問題是如果使用:
{
HtmlGenericControl dodaj = new HtmlGenericControl("button");
dodaj.InnerText = "something";
dodaj.Attributes.Add("runat", "server");
dodaj.Attributes.Add("type", "submit");
dodaj.Attributes.Add("onclick","addKosarica");
newDivInfo.Controls.Add(dodaj);
sadrzaj.Controls.Add(newDivInfo);
this.Controls.Add(sadrzaj);
}
protected void addKosarica(object sender, EventArgs e)
{
Response.Redirect("www.google.com"); //just to see if it triggers
}
我得到:
“未捕獲的ReferenceError:在HTMLButtonElement.onclick中未定義addKosarica”
嘗試谷歌搜索錯誤,這是關於JavaScript的...
然后在進一步搜索之后,我嘗試了:
{
Button dodaj = new Button;
dodaj.Text = "something";
dodaj.Click += new EventHandler("addKosarica");
newDivInfo.Controls.Add(dodaj);
sadrzaj.Controls.Add(newDivInfo);
this.Controls.Add(sadrzaj);
}
protected void addKosarica(object sender, EventArgs e)
{
Response.Redirect("www.google.com");//just to see if it triggers
}
我得到
“必須將類型為“按鈕”的控件“ ctl07”放置在帶有runat = server的表單標記中。”
這是我的aspx代碼:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="11001.aspx.cs" Inherits="_11001" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
(不多是因為我動態地添加了所有內容,並且除了按鈕onclick處理程序之外,其他所有內容都可以正常工作...)
拜托,有人能告訴我如何使它工作嗎?
編輯:sadrzaj是一個div,其中包含我要添加的所有這些元素。 我將它們添加到正在從Page_Load()調用的函數中
抱歉,您對按鈕服務器端和按鈕客戶端端感到非常困惑。
第一個問題是:為什么不在aspx中添加按鈕?
您是否需要循環訪問集合並創建許多類似的按鈕? 您可以使用中繼器。
然后,閱讀代碼...您擁有一個母版頁(我希望包含一個標簽形式runat="server"
)。 您必須將ID添加到要添加的控件中。
在第一段代碼中,您使用以下命令創建了onclick客戶端(因此javascript)
dodaj.Attributes.Add("onclick","addKosarica");
因此,您可以刪除:
protected void addKosarica(object sender, EventArgs e)
{
Response.Redirect("www.google.com");//just to see if it triggers
}
並在aspx文件中添加函數addKosarica()。
在第二段代碼中,正確的代碼是:
dodaj.Click += myButton_Click;
正確的事件是
protected void myButton_Click(object sender, EventArgs e)
並且您可以在Visual Studio中自動創建標簽,在+ =之后單擊兩次標簽
我還建議不要直接使用this.Controls:它是指頁面。 您可以在Content標記中添加PlaceHolder控件或Panel控件,然后向其添加控件。 如果您使用this
而不是Panel
或PlaceHolder
,請嘗試使用this.Form.Controls.Add
您可以參考:
protected void Page_Load(object sender, EventArgs e)
{
Button dodaj = new Button();
dodaj.Text = "Click Me!";
dodaj.Attributes.Add("runat", "server");
dodaj.Attributes.Add("type", "submit");
dodaj.Attributes.Add("onclick", "addKosarica");
newDivInfo.Controls.Add(dodaj);
dodaj.Click += Dodaj_Click1;
}
private void Dodaj_Click1(object sender, EventArgs e)
{
Response.Write("Ok");
}
aspx代碼
<div runat="server" id="newDivInfo">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.