0

我有两个用户控件。每个用户控件都包含一个 ListView。这两个用户控件的目的是显示主/明细数据。引发事件 ResourceReassigned 时,始终会引发空引用异常。我做错了什么,这意味着我的事件处理程序分配不起作用?

<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();
  }

}
4

2 回答 2

1

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

if (ResourceReassigned != null)
    ResourceReassigned(sender, EventArgs.Empty);
于 2012-12-14T11:16:12.590 回答
1

我认为你应该每次都绑定你的事件(不仅在页面没有回发的情况下)。例如在 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);
        }
       }

}

于 2012-12-17T08:34:59.847 回答