You do not want to couple your form with the class that searches and find words from a file.
Here is an Event-based solution
Basically what you have to do is to expose an event in the class that reads and find words from a file (I named it as WordFinder
for an illustration.)
WordFinder
exposes an event called WordFound
that is raised when a new word is found.
public class WordFinder
{
public event EventHandler<WordFoundEventHandler> WordFound = delegate { };
public event EventHandler NoWordsFound = delegate { };
protected virtual void OnWordFound(WordFoundEventHandler e)
{
var wordFoundHandler = WordFound;
wordFoundHandler(this, e);
}
private void OnNoWordsFound(EventArgs e)
{
var noWordsFoundHandler = NoWordsFound;
noWordsFoundHandler(this, e);
}
public void FindWords(string fileName)
{
//.. read file and find word
//.. When a word is found,
OnWordFound(new WordFoundEventHandler(foundWord));
// Keep a counter somewhere and check if any words has been found,
// if no words are found, then raise "NoWordsFoundEvent"
OnNoWordsFound(EventArgs.Empty);
}
}
public class WordFoundEventHandler : EventArgs
{
public string FoundWord { get; private set; }
public WordFoundEventHandler(string foundWord)
{
FoundWord = foundWord;
}
}
Now your form would simply register to the event of WordFinder
and add a new item when a new word is found.
public partial class Form1 : Form
{
private readonly WordFinder _WordFinder;
public Form1()
{
InitializeComponent();
_WordFinder = new WordFinder();
_WordFinder.WordFound += WordFinder_WordFound;
_WordFinder.NoWordsFound += WordFinder_NoWordsFound;
}
private void WordFinder_WordFound(object sender, WordFoundEventHandler e)
{
// Add item to the list here.
foundWordsListBox.Items.Add(e.FoundWord);
}
private void WordFinder_NoWordsFound(object sender, EventArgs e)
{
MessageBox.Show("No words found!");
}
private void findWordsButton_Click(object sender, EventArgs e)
{
_WordFinder.FindWords(/* pass file name here */);
}
}