Reputation: 1
I've been doing a school project and I have a very poor understanding of C#
If a user inputs a certain name in a textbox and presses a button, it will compare each line of a text file to see if that name already exists in the text file named "NameList".
This is what I have so far and it doesn't seem to be working
string substring = txtSearch.Text;
string[] list = System.IO.File.ReadAllLines("NameList.txt");
foreach (string s in list)
{
if (substring == s)
{
lblUnsafe.Visible = true;
lblSafe.Visible = false;
}
else
{
lblUnsafe.Visible = false;
lblSafe.Visible = true;
}
}
When i input a name that is already in the text file, lblSafe becomes visible, which shouldn't happen.
I'm quite bad at explaining, i apologise, im happy to elaborate further if needed, thanks!
Upvotes: 0
Views: 103
Reputation: 186668
You can
substring
is not foundbreak
the loop on first findingCode:
string substring = txtSearch.Text;
string[] list = ...
// substring is not found yet
lblUnsafe.Visible = false;
lblSafe.Visible = true;
foreach (string s in list)
{
if (substring == s)
{
// substring has been found: we change visibility...
lblUnsafe.Visible = true;
lblSafe.Visible = false;
// and break the loop: we've found what we wanted
break;
}
}
Usually for such problems we query the file with a help of Linq:
using System.IO;
using System.Linq;
...
// Do we have any line in the file such that...
lblUnsafe.Visible = File
.ReadLines("NameList.txt").Any(line => line == txtSearch.Text);
// Safe is just Not Unsafe
lblSafe.Visible = !lblUnsafe.Visible;
Upvotes: 1
Reputation: 28272
Your code is partially correct and you might be on the right way here... however in your code, you loop through all names in "NameList.txt", and set the visibility of lblSafe
and lblUnsafe
depending on if the current line you are looping on matches the textbox.
However once you match it, you continue looping... so let's find what happens:
User inputs: John
, and your file contains Bob, John, Tom
.
Your code does:
lblSafe
to visible
and lblUnsafe
to invisible
lblSafe
to invisible
and lblUnsafe
to visible
lblSafe
to visible
and lblUnsafe
to invisible
So the end state is that lblSafe
becomes visible.
What you want to do instead is:
I'll leave the code to you, but it should be pretty easy, and except for a break
statement to add, it's just reorganizing your own code
Upvotes: 1