I have a LINQ query attached to a ‘Next’ button. I want to display the results in some fields inside a form. As of right now I can only show one element when I press the ‘Next’ button, when I press the ‘Next’ button one more time nothing happens
private void btnNext_Click(object sender, EventArgs e)
{
btnPrevious.Enabled = true;
int count = 1;
var elements =
from element in list
select element;
if(count <= elements.Count())
{
FName.Text = elements.ElementAt(count).fName;
LName.Text = elements.ElementAt(count).lName;
Phone.Text = elements.ElementAt(count).Phone;
Gpa.Text = elements.ElementAt(count).Gpa.ToString();
count++;
}
}
Basically, every time I press the ‘Next’ button I want to keep displaying the elements in the list until it reaches the end of the list.
You are re-initialising your count to 1 every time Next is pressed. Move the variable declaration to a private instance field:
You also need to change
countto be zero-indexed, sinceElementAtis zero-indexed. Simply initialisecountto 0, and change your condition to readif (count < elements.Count()).Note that in your code you can use the LINQ extension methods on
listdirectly, bypassing the need to createelements.