Reputation: 3
My goal is to add newly created Student's parameters from TextBox to List collection.
As far as I understand, the code below does not do so.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
btnCreateStudent.Click += btnCreateStudent_Click;
}
private void btnCreateStudent_Click(object sender, RoutedEventArgs e)
{
Student student = new Student();
student.Name = txtFirstName.Text;
student.Surname = txtLastName.Text;
student.City = txtCity.Text;
student.Students.Add(student);
txtFirstName.Text = "";
txtLastName.Text = "";
txtCity.Text = "";
}
class Student
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string surname;
public string Surname
{
get { return surname; }
set { surname = value; }
}
private string city;
public string City
{
get { return city; }
set { city = value; }
}
public List<Student> Students = new List<Student>();
}
}
Upvotes: 0
Views: 3431
Reputation: 80
Your code seems fine to add it into a list. Of course if you want to add the list into a listbox you can easily do it by doing something like this:
Make a ListBox tag in your XAML:
<ListBox Name="studentList"/>
Than in your codebehind:
studentList.Items.Add(student);
In fact you wouldn't need no List at all just initializing the student objects and fill them in.
Upvotes: 0
Reputation: 1639
Have you bound the List<Student> Students
with the ListBox in frontend. Use Data Binding in WPF. That way as soon as you update data, UI is updated automatically.
Here's the code. In XAML:
<DataTemplate x:Key="StudentTemplate">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
<ListBox Name="listBox" ItemsSource="{Binding}"
ItemTemplate="{StaticResource StudentTemplate}"/>
Here is a tutorial on it:
http://www.wpf-tutorial.com/listview-control/listview-data-binding-item-template/
Upvotes: 2