Help with c# event listening and usercontrols

2019-09-06 23:31发布

OK so I have a page which has a listview on it. Inside the item template of the listview is a usercontrol. This usercontrol is trying to trigger an event so that the hosting page can listen to it. My problem is that the event is not being triggered as the handler is null. (ie. EditDateRateSelected is my handler and its null when debugging)

   protected void lnkEditDate_Click(object sender, EventArgs e)
    {
            if (EditDateRateSelected != null)
            EditDateRateSelected(Convert.ToDateTime(((LinkButton)frmViewRatesDate.Row.FindControl("lnkEditDate")).Text)); 
    }

On the item data bound of my listvew is where I'm adding my event handlers

protected void PropertyAccommodationRates1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    if (e.Item.ItemType == ListViewItemType.DataItem)
    {
        UserControls_RatesEditDate RatesViewDate1 = (UserControls_RatesEditDate)e.Item.FindControl("RatesViewDate1");
        RatesViewDate1.EditDateRateSelected += new UserControls_RatesEditDate.EditDateRateEventHandler(RatesEditDate1_EditDateRateSelected);

        RatesViewDate1.PropertyID = (int)Master.PropertyId;
        if (!String.IsNullOrEmpty(Accommodations1.SelectedValue))
        {
            RatesViewDate1.AccommodationTypeID = Convert.ToInt32(Accommodations1.SelectedValue);
        }
        else
        {
            RatesViewDate1.AccommodationTypeID = 0;
        }

        RatesViewDate1.Rate = (PropertyCMSRate)((ListViewDataItem)e.Item).DataItem;
    }
}

My event code all works fine if the control is inside the page and on page load I have the line:

RatesEditDate1.EditDateRateSelected += new UserControls_RatesEditDate.EditDateRateEventHandler(RatesEditDate1_EditDateRateSelected);

But obviously I need listen for events inside the listviewcontrols.

Any advice would be greatly appreciated. I have tried setting EnableViewState to true for my listview but that hasn't made a difference. Is there somewhere else I'm supposed to be wiring up the control handler?

Note - apologies if I've got my terminology wrong and I'm referring to delegates as handlers and such :)

1条回答
放我归山
2楼-- · 2019-09-07 00:04

OK I tried wiring the event to my user control in the source like so:

<uc1:RatesEditDate ID="RatesViewDate1" runat="server" OnEditDateRateSelected="RatesEditDate1_EditDateRateSelected" /> 

and then found it complaining about it being inaccessible due to its protection level. Inside my usercontrol though - I've made my delegate and event public ???

public delegate void EditDateRateEventHandler(DateTime theDateTime); 
public event EditDateRateEventHandler EditDateRateSelected; 

Turns out that within my hosting page - my event handler had no accessiblity defined on it (so was private) - so it needed to be made protected and hey presto was happy!

Problem solved!

查看更多
登录 后发表回答