This is very rough but shows you how you can do it either using a method or an event. If
FormMain
needs to request the labels then use the
by method approach. If the class needs to tell the form that it has labels ready then use the
by event way.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
namespace LabelsGenerator
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
Shown += new EventHandler(FormMain_Shown);
}
void FormMain_Shown(object sender, EventArgs e)
{
LabelMaker labelMaker = new LabelMaker();
Controls.AddRange(labelMaker.MakeLabelsByReturn(2));
labelMaker.LabelsMade += new EventHandler<LabelsMadeEventArgs>(labelMaker_LabelsMade);
labelMaker.MakeLabelsByEvent(2);
}
void labelMaker_LabelsMade(object sender, LabelsMadeEventArgs e)
{
Controls.AddRange(e.Labels);
}
}
public class LabelMaker
{
public event EventHandler<LabelsMadeEventArgs> LabelsMade;
public Label[] MakeLabelsByReturn(int howMany)
{
return MakeLabels(howMany).ToArray();
}
public void MakeLabelsByEvent(int howMany)
{
OnLabelsMade(new LabelsMadeEventArgs(MakeLabels(howMany)));
}
private List<Label> MakeLabels(int howMany)
{
List<Label> result = new List<Label>(howMany);
if (howMany > 0)
{
for (int i = 0; i < howMany; i++)
result.Add(new Label());
}
return result;
}
protected virtual void OnLabelsMade(LabelsMadeEventArgs e)
{
EventHandler<LabelsMadeEventArgs> eh = LabelsMade;
if (eh != null)
eh(this, e);
}
}
public class LabelsMadeEventArgs : EventArgs, IEnumerable<Label>
{
private List<Label> labels;
public LabelsMadeEventArgs(IEnumerable<Label> collection)
{
labels = new List<Label>(collection);
}
public Label this[int index]
{
get { return labels[index]; }
}
public Label[] Labels
{
get { return labels.ToArray(); }
}
IEnumerator<Label> IEnumerable<Label>.GetEnumerator()
{
return (labels as IEnumerable<Label>).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return (labels as IEnumerable).GetEnumerator();
}
}
}