1

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

Leir
  • 33
  • 3
  • else? if s does not equal null, show the form, otherwise, show a messagebox.. else { Messagebox.show("xxx") } Yeah, also the singleordefault others have stated. I didn't scroll all the way to the right, assumed if you were doing a null check it was already there.. mb – Aaron Sep 23 '16 at 15:02
  • 2
    Switch to `db.Students.SingleOrDefault()`. – itsme86 Sep 23 '16 at 15:02

2 Answers2

3

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.

Maor Veitsman
  • 1,544
  • 9
  • 21
-1

As Aaron suggested, an else block will suffice in this case, if you use SingleOrDefault instead. In general, you can use the Any() function to test if any element exists (in your case, combined with a Where())

eavidan
  • 5,324
  • 1
  • 13
  • 16