从另一个用户控件刷新用户控件中的列表视图



我有两个用户控件。每个用户控件都包含一个列表视图。这两个用户控件的目的是显示大纲/详细信息数据。引发事件资源重新分配时,始终会引发空引用异常。我做错了什么,意味着我的事件处理程序分配不起作用?

<asp:ListView ID="lvStaffer" runat="server">
  <LayoutTemplate>
    <table>
      <tr id="itemplaceholder" runat="server"></tr>
    </table>
  </LayoutTemplate>
  <ItemTemplate>
    <tr>
      <td>                    
        <asp:UpdatePanel ID="upResourceListViewControlItem" runat="server">
          <ContentTemplate>
            <rw:ResourceListViewControl ID="ResourceListViewControlItem" runat="server" />
          </ContentTemplate>
        </asp:UpdatePanel>
      </td>
    </tr>
  </ItemTemplate>
</asp:ListView>

public partial class Control_ResourceListViewControl : StafferWebControlBase
{
  public event EventHandler ResourceReassigned;
  protected void lvResource_ItemUpdating(Object sender, ListViewUpdateEventArgs e)
  {
    // If an item in lvResource is updated we want to refresh the master lvStaffer
    // ListView so we raise an event. Null Reference Exception is thrown here. 
    ResourceReassigned(sender, new EventArgs());
  }
}
public partial class Control_StafferListViewControl : StafferWebControlBase
{
  protected void lvStaffer_ItemDataBound(Object sender, ListViewItemEventArgs e)
  {
    Control_ResourceListViewControl resourceListViewControlItem =
(Control_ResourceListViewControl)e.Item.FindControl("ResourceListViewControlItem");
    if (resourceListViewControlItem != null)
    {
      // Each item in lvStaffer contains an instance of the ResourceListViewControl object.
      // Each object is a subscriber of the ResourceReassigned event.
      resourceListViewControlItem.ResourceReassigned += new EventHandler(lvStaffer_ResourceReassigned);
    }
  }
  protected void lvStaffer_ResourceReassigned(object sender, EventArgs e)
  {
    // Repopulates and binds the lvStaffer ListView
    ResetStafferListView();
  }
}

我认为您应该每次都绑定您的事件(不仅在页面未回发的情况下)。 例如Page_Load事件或控件 OnLoad。

  protected void Page_Load(object sender, EventArgs e){     
  foreach (ListViewItem item in lvStaffer.Items)
        {
           Control_ResourceListViewControl resourceListViewControlItem =
        (Control_ResourceListViewControl)e.Item.FindControl("ResourceListViewControlItem");
        if (resourceListViewControlItem != null)
        {
           // Each item in lvStaffer contains an instance of the          ResourceListViewControl object.
          // Each object is a subscriber of the ResourceReassigned event.
           resourceListViewControlItem.ResourceReassigned += new   EventHandler(lvStaffer_ResourceReassigned);
        }
       }

}

NullReferenceException是因为在引发事件时没有订阅者。虽然您可以在 VB.NET 中安全地调用"RaiseEvent",但在 C# 中,您首先需要检查事件对象是否未null

if (ResourceReassigned != null)
    ResourceReassigned(sender, EventArgs.Empty);

相关内容

  • 没有找到相关文章

最新更新