2017-06-07 180 views
0

我試圖創建LinkButtons控件動態OnClick另一個按鈕,即頁面加載後。例如:我有一個名爲添加控件的按鈕,其功能是動態添加鏈接按鈕,併爲所有動態添加事件處理程序動態創建鏈接按鈕。但不幸的是,事件不會被觸發。以下是我所做的一段代碼。LinkBut​​ton onclick事件不會觸發動態創建按鈕c#

假設DomainList.Items是五個元素的集合。

protected void AddControls_Click(object sender, EventArgs e) 
{ 
    foreach (ListItem item in DomainList.Items) 
    {    
     LinkButton deleteDomain = new LinkButton(); 

     deleteDomain.Text = "Delete"; 
     deleteDomain.Click += new System.EventHandler(deleteDomain_Click); 
     deleteDomain.ClientIDMode = ClientIDMode.Static; 
     deleteDomain.CommandArgument = item.Text; 
     divEditDomainName.Controls.Add(deleteDomain); 

    } 
} 

void deleteDomain_Click(object sender, EventArgs e) 
{ 
    //Some Code; 
} 

以下是我的頁面加載代碼。

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      Label lblEvent = this.Master.FindControl("SpEvent") as Label; 
      if (Session["eventname"] != null) 
      { 
       lblEvent.Text = Session["eventname"].ToString() + " " + "<i class='fa fa-angle-down'></i>"; 
      } 
      Image imgEvent = this.Master.FindControl("ImageEvent") as Image; 
      imgEvent.ImageUrl = Convert.ToString(Session["ImageURL"]); 
      lblCreateOrganization.Text = Convert.ToString(Session["eventname"]); 

      BindOrganization(); 
      EditOrganizationID.Attributes.Add("readonly", "readonly"); 
     } 

    } 

deleteDomain_Click事件未被觸發。我希望觸發點擊事件。

+0

[asp.net動態與事件處理程序按鈕]的可能的複製(https://stackoverflow.com/questions/7713242/asp-net-dynamically-button-with-event-處理程序) –

+0

可以請你分享你的page_load事件代碼 –

+0

@ArsalanQaiser請檢查上面。 –

回答

1

當點擊事件觸發器時,回發會發生,所以他們重新創建並重新附加到事件處理程序。

創建(和重新創建)動態控件的最佳位置是在page_load或page_init事件處理程序中。

試試這個

public bool AddControlsClicked 
    { 
     get 
     { 
      return Convert.ToBoolean(ViewState["AddControlsClicked"]); 
     } 
     set 
     { 
      ViewState["AddControlsClicked"] = value; 
     } 
    } 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     if(AddControlsClicked) 
     { 
      for (int i = 0; i < 5; i++) 
      { 
       LinkButton deleteDomain = new LinkButton(); 

       deleteDomain.Text = "Delete"; 
       deleteDomain.Click += new System.EventHandler(deleteDomain_Click); 
       //deleteDomain.ClientIDMode = ClientIDMode.Static; 
       //deleteDomain.CommandArgument = item.Text; 
       divEditDomainName.Controls.Add(deleteDomain); 
      } 
     } 
    } 

    void deleteDomain_Click(object sender, EventArgs e) 
    { 
     //Some Code; 
    } 

    protected void AddControls_Click(object sender, EventArgs e) 
    { 
     AddControlsClicked = true; 
     Page_Load(sender, e); 
    } 
相關問題