Ali Zangeneh
Ali Zangeneh

Reputation: 77

'Sequence contains no elements', happening?

It's a WINDOWSFORM

I have combobox, I use this code for auto textboxvalue but I receive this error

Sequence contains no elements

private void cmbOfficeNumber_SelectedIndexChanged(object sender, EventArgs e)
{
    using (UnitOfWork db = new UnitOfWork())

    if (cmbOfficeNumber.SelectedValue.ToString() != null)
    {
        txtOfficeName.Text = db.OfficeRepository.GetOfficeNamebyNumber(cmbOfficeNumber.Text);

    }
}

And this is my repository code

public string GetOfficeNamebyNumber(string officeNumber)
{
    return db.Office.First(g => g.OfficeNumber == officeNumber).OfficeName;
}

EDIT: When using

return db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber).OfficeName;

I receive a different error

Object reference not set to an instance of an object

Upvotes: 0

Views: 7879

Answers (2)

calvin banhwa
calvin banhwa

Reputation: 1

Or, if your class fields are defined without an access type public/private you will have the same error.. Happened to me. just had to go back to the class and specify the access type as public int [myVariable] and it worked

Upvotes: 0

Davey van Tilburg
Davey van Tilburg

Reputation: 718

If First() results in

Sequence contains no elements

That means the condition in the lambda expression resulted in no hits. Because First requires you to have atleast one match.

If FirstOrDefault().Property results in

Object reference not set to an instance of an object

It means that the lambda expression resulted in no hits, and it returns a default value of the return type. In the case of a reference object it will be null. You then tried to access a property of null which causes the exception.

Simply put. Your problem is that your comparison is returning no hits.

You need to insert a fail safe for this to not crash

Something like:

public string GetOfficeNamebyNumber(string officeNumber)
{
    var result = db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber);

    if(result == null)
        return string.Empty;

    return result.OfficeName;
}

This can also be shortend to

public string GetOfficeNamebyNumber(string officeNumber)
{
    var result = db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber);

    return result?.OfficeName ?? string.Empty;
}

Or even

public string GetOfficeNamebyNumber(string officeNumber)
{
    return db.Office.FirstOrDefault(g => g.OfficeNumber == officeNumber)?.OfficeName ?? string.Empty;
}

I hope this step by step explanation gives you the information you need to solve the problem.

Upvotes: 1

Related Questions