简体   繁体   中英

To call a method in usercontrol from another user control in asp.net

In the below code I have 2 user controls sample.ascx and sample1.ascx .I have a button in sample.ascx when I click the button it should call the method in sample1.ascx . Pls help me to do this.

Sample.ascx

<%@ Register TagPrefix="gmas" TagName="FieldCont" Src="~/Controls/Sample1.ascx" %>
<asp:Button id="Savebtn" runat="server" Text="Save" OnClick="Save_Click"  />

CodeBehind:

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

Sample1.ascx

public bool IsValid()
{
}
 protected void Save_Click(object sender, EventArgs e)
        {

         Sample1 ctrlB = new Sample1();

            ctrlB.IsValid();
      }

Make sure your user control code behind is Sample1 as mentioned below :

public partial class Sample1 : System.Web.UI.UserControl

and you can call IsValid method in button click event as mentioned below :

var control = new Sample1();
var isvalid = control.IsValid();

Note:

  • IsValid method inside Sample1.ascx.cs should be public
  • Namespace of 'Sample1' should be same as 'Sample'. If both are having different namespace then namespace of 'Sample1' should be included in 'Sample' by using directive

我认为它必须简单,你可以尝试使用代码。

(new sample1()).<functionTocall>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM