c# - 如何从用户控件调用一个方法到aspx页面?

标签 c# asp.net user-controls

我想从用户控件调用一个方法到aspx页面

我正在尝试,但我无法在 aspx 页面中调用该方法

代码:

AddVisaUserControl.ascx.cs

public event EventHandler UserControlButtonClicked;

    public void OnUserControlButtonClick()
    {
        if (UserControlButtonClicked != null)
        {
            UserControlButtonClicked(this,EventArgs.Empty);
        }
    }

protected void btnRemove_Click(object sender, EventArgs e)
    {
        OnUserControlButtonClick();
    }

.aspx

编辑

在下面的代码中,当页面加载时出现“空引用错误”

AddVisaControl av; 
protected void Page_Load(object sender, EventArgs e)
    {
        av.UserControlButtonClicked  += new
                EventHandler(AddVisaUserControl_UserControlButtonClicked);
    } 

  private void AddVisaControl_UserControlButtonClicked(object sender, EventArgs e)
    {
        var ctrl = (AddVisaControl)LoadControl(@"AddVisaControl.ascx");
        //ctrl.ID = i;
        this.rpt1.Controls.Remove(ctrl);
    }

有什么想法吗?提前致谢

最佳答案

您似乎有一个未初始化的字段:

AddVisaControl av; 

其默认值为 null,因此为 NullReferenceException。

如果您已将 UserControl 的实例添加到您的 aspx 页面,您应该有一个名称等于 UserControl 实例 ID 的实例:

=== 在 Page.aspx 中

<uc1:AddVisaUserControl ID="MyControl" ... />

=== 在 Page.aspx.cs 中

MyControl.UserControlButtonClicked += ...

关于c# - 如何从用户控件调用一个方法到aspx页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19027066/

相关文章:

c# - 如何让 Null Coalesce 运算符在 ASP.NET MVC Razor 中工作?

C# Web API POST 时出现错误 404

c# - 如何访问用户控件页面 ListView 中动态创建的表的文本框?

Silverlight 用户控件和 MVVM

ASP.NET:响应中的全局 Hook ?

c# - 将 UserControl 转换为自定义控件

c# - ASP.NET MVC,创建将多个对象返回到 View 的 View 方法

c# - 为什么我的 Parallel.ForAll 调用最终使用单个线程?

c# - asp 标签的字符数限制为 1000 个字符

asp.net - 在 IIS URL 重写模块中自定义 HTTP header