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 .
Best Answer
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 fornull
, such as:Chances are your loop is resulting in an "off by one" error.