Reputation: 33
I am facing problem in considering the if/else statements in the following piece of code. Actually I want to tell my user if the word from the file is not found my code must shows an error message else my code must go to show a new form, here's my code:
public void searchGlossary(String word)
{
StringBuilder description = new StringBuilder(512);
string descLine;
using (StreamReader reader = File.OpenText("C:/Users/--- /Desktop/--- .txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith(word, StringComparison.OrdinalIgnoreCase))
{
// At this point we've already read the keyword and it matches our input
// Here we start reading description lines after the keyword.
// Because every keyword with description is separated by blank line
// we continue reading the file until, the last read line is empty
// (separator between keywords) or its null (eof)
while ((descLine = reader.ReadLine()) != string.Empty && descLine != null)
{
description.AppendLine(descLine);
}
//descbox.Text = description.ToString();
isfound = true;
DomainExpertForm form = new DomainExpertForm(keyword, description.ToString());
form.Show();
break;
}
}
if (isfound == false)
{
MessageBox.Show("No Matches found for Word " + word, "Domain Expert Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
The problem is that if the word is not found it always shows me form instead showing an error message. What's the problem and the solution can somebody help me I am new c#!
Upvotes: 0
Views: 150
Reputation: 33
what i need was to check if the required word was found and if not I want to show the Error Dialogue so here is my solution:
I simply checked the length of the found string; if its ==0 i show up an error message as:
if (description.ToString().Length==0)
{
MessageBox.Show("No Matches found for Word " + word, "Domain Expert Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
and here I go found this solution myself!
Upvotes: 0
Reputation: 4727
You should declare and initialise isFound
with false
at the beginning of your method:
public void searchGlossary(String word)
{
var isFound = false;
StringBuilder description = new StringBuilder(512);
...
}
Upvotes: 5