Leir Leir - 2 months ago 12
C# Question

If sequence contains no elements show message box

I'm creating a log in form in c# using this code

DataclassesDatacontext db = new DataclassesDatacontext();
Student s = null

s = db.Students.Single(r => r.Username == textboxUname.Text && r.Password == textboxPword.Text);
if (s != null)
{
form1 frm = new form1();
frm.Show();
}


if the user inputs a valid account, form1 will show but if the user inputs invalid account or the username and password he entered does not exist in the database, i'll get an error on the third line saying "sequence contains no elements".

Now my problem is, how to show a message box if the sequence contains no elements without using try catch.

Thanks in advance

Answer

I assume that Single is the cause of the exception. You should use SingleOrDefault instead.

s = db.Students.SingleOrDefault(r => r.Username == textboxUname.Text && r.Password == textboxPword.Text);

When the collection is empty, SingleOrDefault shall return null instead of throwing an exception like the function Single.