user2376998
user2376998

Reputation: 1071

LINQ Entity Framework sequence contains no elements

i have a database table that looks like this :

enter image description here

i am trying to retrieve the textboxValue with reference to the textboxID like this :

   public string GetPuzzle(string tid)
   {
       return context.crosswords.First(c => c.TextBoxID == tid).TextBoxValue;
   }

The above code ( CRUD class file ) gave me an error : System.InvalidOperationException: Sequence contains no elements

I have 100 text boxes created in a panel using 2 for loops , each text box have an id from 00-99 , so i am trying to append the textBoxValue to the text of the textboxes in the loop with reference to the textBoxID as the database above.

And the below code is how i try to do it , don't know if it is the correct way :

protected void Page_Load(object sender, EventArgs e)
{      
    for (int i = 0; i <= 9; i++)
    {           
        for (int j = 0; j <= 9; j++)
        {                
            TextBox tb = new TextBox();
            tb.MaxLength = (1);
            tb.Width = Unit.Pixel(40);
            tb.Height = Unit.Pixel(40);
            tb.ID = i.ToString() + j.ToString(); // giving each textbox a different id  00-99 
            Panel1.Controls.Add(tb);
            tb.Enabled = false;

            tb.Text = daoCrossword.GetPuzzle(tb.ID).ToString();
        } 

        Literal lc = new Literal();
        lc.Text = "<br />";
        Panel1.Controls.Add(lc);
    }
}

i am trying to select textboxvalue where textboxid = tid . tid will be my tb.ID in code behind and since there is 100 loops , every time tb.ID will increase from 00-99 , so when it reach an ID that contains a value in database , it will append the textboxvalue ( from database) to that textbox and so on .

Upvotes: 2

Views: 5678

Answers (3)

TGH
TGH

Reputation: 39248

Looks like an error in your algorithm for declaring ids. The Linq query is failing because it's being passed an invalid id

I would inspect the id that causes the exception.

Upvotes: 1

pztx1992
pztx1992

Reputation: 11

Because you are using 2 for-loops to create IDs for TextBox, each one has an id from 00 to 99

but actually TextBoxID column values are like 0,1,2,3,4,5.

the generated IDs are not in textboxid column.

so this code:

return context.crosswords.First(c => c.TextBoxID == tid).TextBoxValue;

error

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65079

That error is thrown when no elements are returned from your query. You are asking for .TextBoxValue on nothing. Consider using .FirstOrDefault() by itself, and checking for null, such as:

var crossword = context.crosswords.FirstOrDefault(c => c.TextBoxID == tid);

if (crossword != null) {
    crossword.TextBoxValue;
}
else {
    // error.. not found
}

Chances are your loop is resulting in an "off by one" error.

Upvotes: 4

Related Questions