Reputation: 1071
i have a database table that looks like this :
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
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
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
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