在我的ASP.Net页面中,我有PlaceHolder和Button。当用户单击此按钮时,我将一些UserControls从我的接口方法getControl添加到PlaceHolder。代码:
protected void ActionBtn_Click(object sender, EventArgs e)
{
if (provider != null)
{
actualObject = (PlaceHolder)provider.getControl();
PlaceHolder1.Controls.Add(actualObject);
}
}
方法getControl:
public object getControl()
{
ph = new PlaceHolder();
exportInbBtn = new Button();
exportInbBtn.Text = "Export Inventury";
exportInbBtn.Click += new EventHandler(myButton_ServerClick);
ph.Controls.Add(exportInbBtn);
exportInbBtn.ID = "exportInbBtn";
return ph;
}
ASP页面中的方法Page_Load和Page_Init为空。问题是,当用户单击按钮exportInbBtn(带有文本:“Export Inventury”)时,单击事件myButton_ServerClick将不会上升。只有网页刷新。我准备了一些答案,但我无法想象如何轻松解决这个问题。
答案 0 :(得分:5)
如果您触发* myButton_ServerClick *事件,则会调用回发并且ASP.Net想要触发调用事件,但您的控件未添加到页面中,这就是ASP.Net忽略此事件的原因。
在回发之后和要触发的事件之前,你必须再次添加你的控件,在它们之后,将调用事件。
<强>更新强>
像这样的东西
Page:
<asp:Button runat="server" ID="btnTest" Text="Add control" OnClick="btnTest_Click"/>
<asp:Label runat="server" ID="result"></asp:Label>
<asp:HiddenField runat="server" ID="controlLoaded"/>
<asp:PlaceHolder runat="server" ID="phTest"></asp:PlaceHolder>
代码背后:
protected void Page_Load(object sender, EventArgs e)
{
if (controlLoaded.Value == "1")
{
AddControl();
}
}
protected void btnTest_Click(object sender, EventArgs e)
{
AddControl();
}
protected void myButton_ServerClick(object sender, EventArgs e)
{
result.Text = "OK";
}
public object getControl()
{
var ph = new PlaceHolder();
var exportInbBtn = new Button();
exportInbBtn.Text = "Export Inventury";
exportInbBtn.Click += new EventHandler(myButton_ServerClick);
ph.Controls.Add(exportInbBtn);
exportInbBtn.ID = "exportInbBtn";
return ph;
}
private void AddControl()
{
var actualObject = (PlaceHolder)getControl();
phTest.Controls.Add(actualObject);
controlLoaded.Value = "1";
}
答案 1 :(得分:1)
请注意,UserControls是通过以下方法添加的 - //首先创建用户控件的实例 var control = Page.LoadControl(“〜/ folder1 / UserControl1.ascx”)
//现在将此控件添加到占位符as - placeHolder1.Controls.Add(control);
我希望这会有所帮助。
答案 2 :(得分:0)
<强> page.aspx 强>
<asp:PlaceHolder ID="PlaceHolder1" runat="server" ></asp:PlaceHolder>
<强> page.aspx.vb 强>
Private Sub CreateControl()
Dim vw As Control
vw = CType(LoadControl("~/View01.ascx"), View01)
vw.ID = "View_Dyn"
PlaceHolder1.Controls.Clear()
PlaceHolder1.Controls.Add(vw)
End Sub
每回发重新创建
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
CreateControl()
End Sub