从用户控件单击按钮单击我的表单(asp.Net)

时间:2012-11-09 11:09:25

标签: c# asp.net events button user-controls

你可以帮助我,告诉我为什么我的代码不正确。 我想创建一个UserControl,它将是一个注册表单。 在这个控件中,我有一个按钮,当单击按钮时,我希望服务器重定向到另一个页面。 这是我的代码:

control.ascx.cs:

public partial class ControlFormulaire : System.Web.UI.UserControl
{
    public event EventHandler ButtonClicked;// it could be named differently obviously
    protected void ValidateButton_Click(object sender, EventArgs e)
    {
               if (this.ButtonClicked != null)
                    ButtonClicked(this, new EventArgs());
    }

    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

form.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    this.SubscribForm.ButtonClicked += new EventHandler(SubscribForm_ButtonClicked); 
}

void SubscribForm_ButtonClicked(object sender, EventArgs e)
{
    Response.Redirect("WebForm2.aspx");
}

那是我的form.aspx:

<%@ Register TagPrefix="uc" TagName="Form" Src="~/ControlFormulaire.ascx"%>
<uc:Form ID="SubscribForm" runat="Server" MinVal="1" MaxVal="10" />

2 个答案:

答案 0 :(得分:0)

请试试这个

public partial class ControlFormulaire : System.Web.UI.UserControl
{
    public event EventHandler ButtonClicked;// it could be named differently obviously
    protected void ValidateButton_Click(object sender, EventArgs e)
    {
           ButtonClicked();
    }

    private void ButtonClicked()
    {
       if (ButtonClicked!= null)
       {
           ButtonClicked(this, EventArgs.Empty);
       }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    ControlFormulaire.ButtonClicked+= new EventHandler(SubscribForm_ButtonClicked);
}

void SubscribForm_ButtonClicked(object sender, EventArgs e)
{
    Response.Redirect("WebForm2.aspx");
}

答案 1 :(得分:0)

this line is the key or the custom click event ignores updatepanel 
// ScriptManager.GetCurrent(Page).RegisterAsyncPostBackControl(this);

and note the IPostBackEventHandler part in page definition

in this example ordinary button and a custom click event div work together inside an update panel

public partial class tmp2 : System.Web.UI.Page, IPostBackEventHandler {

protected void Page_Load(object sender, EventArgs e) { ScriptManager.GetCurrent(Page).RegisterAsyncPostBackControl(this); if (!Page.IsPostBack) { div1.Attributes["onclick"] = ClientScript.GetPostBackEventReference(this, "ClickDiv"); } } protected void Button1_Click(object sender, EventArgs e) { Label1.Text += "1"; UpdatePanel1.Update(); } protected void Div1_Click() { div1.InnerHtml += "b"; UpdatePanel1.Update(); } public void RaisePostBackEvent(string eventArgument) { if (!string.IsNullOrEmpty(eventArgument)) { if (eventArgument == "ClickDiv") { Div1_Click(); } } }

}