Reputation: 21
For some reason my Else statement is always being executed even when the if statement is.
string line;
string[] columns = null;
while ((line = sr.ReadLine()) != null)
{
columns = line.Split(',');
if (columns.Contains(tboxName.Text))
{
rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
}
else
{
MessageBox.Show("No Hotels Found.");
break;
}
Is this because it is searching through every line in the file because of the while loop and not every line contains tboxName?
If so how would it be able to return all values of column[0] without using a while loop?
Upvotes: 0
Views: 90
Reputation: 608
Try something like this
string[] columns = null;
var isHotels = false;
while ((line = sr.ReadLine()) != null)
{
columns = line.Split(',');
if (columns.Contains(tboxName.Text))
{
rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
isHotels = true;
}
} // while loop ends
if (!isHotels)
{
MessageBox.Show("No Hotels Found.");
break;
}
Upvotes: 1
Reputation: 1578
If I understand correctly, you want to show the message box if none of the lines in the file contain tboxName.Text
? If so you can do this check after the while loop completes, using a bool
to track whether any line did have a match:
string line;
string[] columns = null;
bool foundHotels = false;
while ((line = sr.ReadLine()) != null)
{
columns = line.Split(',');
if (columns.Contains(tboxName.Text))
{
rtBoxResults.Text = ((columns[0] + " " + columns[1] + " " + columns[2] + " " + columns[3]));
foundHotels = true;
}
}
if(!foundHotels)
{
MessageBox.Show("No Hotels Found.");
}
Upvotes: 1