0
不費一槍在我的主網頁視圖我有一個LinkButton,一個佔位符,我登記我的用戶:LinkButton的點擊事件動態用戶控件
<%@ Register TagPrefix="vf" TagName="Headline" Src="~/Controls/Headline.ascx" %>
<asp:LinkButton ID="lbAddHeadline" runat="server" OnClick="lbAddHeadline_OnClick">+ Headline</asp:LinkButton>
<asp:PlaceHolder ID="phAddTemplateControlsArea" runat="server"></asp:PlaceHolder>
在這個鏈接按鈕的情況下,我給我的控制的ID根據我添加到頁面的控件數量,我還設置了一個命令arg並鏈接了一個按鈕單擊事件,然後將它們全部加載到面板中。 當我點擊用戶控件按鈕,我希望它火的方法我的主頁上,RemoveItem_OnClick()
protected void lbAddHeadline_OnClick(object sender, EventArgs e)
{
Controls_Headline ctrl = (Controls_Headline)LoadControl("~/Controls/Headline.ascx");
ctrl.ID = "MyCtrl_" + CMSSession.Current.AddedTemplateControls.Count;
ctrl.Remove.CommandArgument = CMSSession.Current.AddedTemplateControls.Count.ToString();
ctrl.RemoveEvent += new EventHandler(RemoveItem_OnClick);
CMSSession.Current.AddedTemplateControls.Add((Control)ctrl);
LoadControlsToPanel();
}
private void LoadControlsToPanel()
{
PlaceHolder ph = accAddTemplates.FindControl("phAddTemplateControlsArea") as PlaceHolder;
foreach (var ctrl in CMSSession.Current.AddedTemplateControls)
{
ph.Controls.Add(ctrl);
}
}
public void RemoveItem_OnClick(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
}
當控件添加到主頁上的面板,我已經覆蓋了的OnInit方法在用戶控件保存數據:
protected override void OnInit(EventArgs e)
{
PlaceHolder ph = accAddTemplates.FindControl("phAddTemplateControlsArea") as PlaceHolder;
int counter = 0;
foreach (UserControl ctrl in CMSSession.Current.AddedTemplateControls)
{
ctrl.ID = "MyCtrl_" + counter;
ITemplateControl ictrl = ctrl as ITemplateControl;
ictrl.Remove.CommandArgument = counter.ToString();
ictrl.RemoveEvent += new EventHandler(RemoveItem_OnClick);
counter++;
ph.Controls.Add(ctrl);
}
base.OnInit(e);
}
正如你所看到的,用戶控件impliments它,和其他用戶控件會用這樣我就可以連接起來,一些常見的按鈕的通用接口
public interface ITemplateControl
{
LinkButton Remove { get; set; }
TextBox Label { get; set; }
event EventHandler RemoveEvent;
}
這是用戶控件的HTML:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Headline.ascx.cs" Inherits="Controls_Headline" %>
<div class="headline">
Headline Text:
<asp:TextBox ID="txtLabel" runat="server"></asp:TextBox>
<asp:LinkButton ID="lbRemove" runat="server" OnClick="lbRemove_OnClick">X</asp:LinkButton>
</div>
這是用戶控件的代碼隱藏:
public partial class Controls_Headline : UserControl, ITemplateControl
{
protected void Page_Load(object sender, EventArgs e)
{
lbRemove.Click += new EventHandler(lbRemove_OnClick);
}
public TextBox Label
{
get { return txtLabel; }
set { txtLabel = value; }
}
public LinkButton Remove
{
get { return lbRemove; }
set { lbRemove = value; }
}
public event EventHandler RemoveEvent;
protected void lbRemove_OnClick(object sender, EventArgs e)
{
if (RemoveEvent != null)
{
RemoveEvent(sender, e);
}
}
}
現在,當我點擊lbRemove的LinkButton位於該用戶控件內,我希望它調用它自己的方法lbRemove_OnClick,然後調用我在OnInit方法中綁定的委託事件。
每次我點擊lbRemove鏈接按鈕時會發生什麼,它會調用主頁的OnInit方法,那就是它。
我錯過了什麼?