我想通过按student.FirstName
从studentsList
输出每个btnNext_Click
,从0值开始到最后一个,点击“下一步按钮”。
我尝试这样做,但是,不知道如何从public static List<Student> studentsList = new List<Student>();
private void btnCreateStudent_Click(object sender, RoutedEventArgs e)
{
addStudent();
Clear();
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
Next();
}
public void addStudent()
{
Student student = new Student();
student.FirstName = txtFirstName.Text;
student.LastName = txtLastName.Text;
student.City = txtCity.Text;
Student.studentsList.Add(student);
}
public void Clear()
{
txtFirstName.Clear();
txtLastName.Clear();
txtCity.Clear();
}
public void Next()
{
foreach (Student student in Student.studentsList)
{
txtFirstName.Text = student.FirstName;
}
}
答案 0 :(得分:3)
使用变量存储学生的索引,并在每次按下时增加一次,这样每次都会获得下一个学生姓名。
例如:
int studentIndex;
public void Next()
{
if (studentIndex >= Student.studentsList.Count - 1)
studentIndex = 0;
txtFirstName.Text = Student.studentsList[studentIndex].FirstName;
studentIndex++;
}
到达最后一名学生后,它将重置为第一名学生。
答案 1 :(得分:2)
您需要将当前状态保留在程序中,以便实现&#34;步进&#34;像那样。您只需要当前索引:在构造函数中初始化它,然后在Next
方法中使用它。完成当前索引后,将其递增,以便下次调用Next
方法时获得后续值。
int currentStudent = 0;
public void Clear() {
txtFirstName.Clear();
txtLastName.Clear();
txtCity.Clear();
currentStudent = 0;
}
public void Next() {
// You need to stop when you reach the end of the list
if (currentStudent < Student.studentsList.Count) {
txtFirstName.Text = Student.studentsList[currentStudent].FirstName;
currentStudent++;
}
}
答案 2 :(得分:1)
尝试将最后一个索引作为类成员存储。
int lastIndexRead = 0;
public void Next()
{
if(lastIndexRead == Student.studentsList.Count) // do something - index is out of bounds of the array
else
{
txtFirstName.Text = Student.studentsList[lastIndexRead].FirstName;
lastIndexRead++;
}
}