c# - 从驻留在转发器控件内的用户控件调用父页面中的方法

标签 c# asp.net user-controls repeater

我遵循了许多其他问题来尝试解决这个问题,但它们似乎不适用于我的情况。 This is an example .

在我的例子中,用户控件的一个实例在转发器中被多次加载,我怀疑这与我遇到的问题有关。

我使用此方法将事件附加到用户控件的每个实例。

  protected void rptPosts_ItemDataBound(object sender, RepeaterItemEventArgs e)
  {
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
      DataRowView MyRow = (DataRowView)e.Item.DataItem;
      Post MyPost = (Post)e.Item.FindControl("Post");

      MyPost.UserControlButtonClicked += new EventHandler(MyPost_UserControlButtonClicked);

      MyPost.LoadPost(MyRow);
    }
  }

  private void MyPost_UserControlButtonClicked(object sender, EventArgs e)
  {
    // reload repeater items
  }

在用户控制代码后面我放了这段代码:

  public event EventHandler UserControlButtonClicked;

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

在用户控件内的按钮中(应该触发页面方法)我把这个:

  protected void lnkDelete_Click(object sender, EventArgs e)
  {
    // Code to delete record //

    OnUserControlButtonClick();
  }

问题似乎是 if (UserControlButtonClicked != null) 似乎总是返回 false,因此 UserControlButtonClicked(this, EventArgs.Empty); 永远不会执行。

最佳答案

您需要将事件挂接到 OnItemCreated。否则,如果您发布该页面,它将消失。所以我希望它看起来像这样:

protected void rptPosts_ItemCreated(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Post MyPost = (Post)e.Item.FindControl("Post");
        MyPost.UserControlButtonClicked += new EventHandler(MyPost_UserControlButtonClicked);
    }
}

然后在 ItemDataBound 中你真的不需要连接事件。所以它看起来像这样:

protected void rptPosts_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
      DataRowView MyRow = (DataRowView)e.Item.DataItem;
      Post MyPost = (Post)e.Item.FindControl("Post");
      MyPost.LoadPost(MyRow);
    }
}

在 ItemDataBound 中,您仍然需要加载帖子。我不建议在 ItemCreated 中这样做。因为这意味着您将在每次创建项目时加载帖子。这不是你想要的

引用:

关于c# - 从驻留在转发器控件内的用户控件调用父页面中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44262834/

相关文章:

c# - 扩展用户控制

c# - 自动更改事件控件的属性

C# MouseLeave 在显示上下文菜单之前触发?

c# - Windows 服务可以自行停止吗?

c# - 为什么我的代码在每个可能的点都关闭它后仍然在进行延迟加载?

asp.net - 在 ASP.NET 中,如何处理 session 和多个选项卡?

c# - 如何在 WPF 的 Combobox 中有效地添加多个项目

c# - 环境事务中的 TransactionScope 错误不会回滚事务

asp.net - 创建 cookie 时,如何指定 www 而不指定 www cookie?

c# - 访问 UserControl 的模板项