Reputation: 9305
(Info): I know this has been asked several times, but IMHO always the issue was that the Event wasn't really added at the calling funcation, which is not the case here.
I have the following class:
public class FilePanel : BasePanel
{
public event LinkClickedEventHandler FileOpen;
private PlaylistElement _element;
public FilePanel() : base()
{
AddControls(new PlaylistElement { Description = "lorem ipsom" });
}
public FilePanel(PlaylistElement element) : base(element)
{
AddControls(element);
}
private void AddControls(PlaylistElement element)
{
_element = element;
ToolTip tt = new ToolTip();
var textControl = new Label { Dock = DockStyle.Fill, Text = element.File.Title, Padding = new Padding(2, 2, 5, 2) };
var linkControl = new LinkLabel { Dock = DockStyle.Right, TextAlign= System.Drawing.ContentAlignment.MiddleRight, Width = 200, Text = "Datei öffnen", Padding = new Padding(2, 2, 5, 2) };
tt.SetToolTip(linkControl, element.File?.FileReference);
linkControl.Click += LinkControl_Click;
this.Controls.Add(textControl);
base.AddControls(element);
this.Controls.Add(linkControl);
this.Height = 50;
}
private void LinkControl_Click(object sender, EventArgs e)
{
FileOpen?.Invoke(this, new LinkClickedEventArgs(_element.File.FileReference));
}
}
This class is called the following way:
private void AddScheduleFile(RadCollapsiblePanel blockPanel, PlaylistElement element)
{
var panel = new ScheduleControls.FilePanel(element);
panel.FileOpen += Panel_FileOpen;
blockPanel.Controls.Add(new ScheduleControls.FilePanel(element));
}
As you can see, the FileOpen-Event is assigned to the calling class.
But when I Break into LinkControl_Click
, FileOpen
is NULL nonetheless.
Upvotes: 3
Views: 131
Reputation: 23732
it seems that you fire the event in the wrong object. Although you register the event you do it for the panel
object. But you add an entirely new object to the controls:
blockPanel.Controls.Add(new ScheduleControls.FilePanel(element));
if you now use this object to fire the event, you will see that it is null
because you have not registered it. Why not passing the original object to the controls?=! :
private void AddScheduleFile(RadCollapsiblePanel blockPanel, PlaylistElement element)
{
var panel = new ScheduleControls.FilePanel(element);
panel.FileOpen += Panel_FileOpen;
blockPanel.Controls.Add(panel);
}
Upvotes: 3