Else statement not working properly in foreach loop? Here’s my code. If something’s wrong with my code explanations would be nice.
protected void getdata_Click(object sender, EventArgs e)
{
using (var db2 = new cftzClassDataContext())
{
var username = (from p in db2.cftzAccounts
where p.username.Equals(getdata2.Text)
select p);
foreach (var p in username)
{
if (getdata2.Text == p.username)
{
displayMSG.Text = "Is this correct ";
displayData.Text = p.username;
displayQuestionMark.Text = "?";
}
else
{
displayMSG.Text = "No User Found.";
}
}
}
}
The
ifstatement is entirely redundant, as you have already filtered your list to only include accounts where the username equalsgetData2.Text. Therefore, youriftest will always evaluate totrue.You can rewrite it as this, with the same effect
However, as Hans points out, your loop is unnecessary as well, as all the usernames will be the same. Your code could be as simple as: