我有两个用户控件。每个用户控件都包含一个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();
}
}
答案 0 :(得分:1)
抛出NullReferenceException
因为在举起活动时没有订阅者。虽然你可以安全地在VB.NET中调用“RaiseEvent”,但在C#中你首先需要检查事件对象是否不是null
:
if (ResourceReassigned != null)
ResourceReassigned(sender, EventArgs.Empty);
答案 1 :(得分: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);
}
}
}