0

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>();
    }
}
2
  • A List, or a ListBox? Commented May 9, 2015 at 3:12
  • A List. I need it to store data input made by a user of the Form in order to later use it to display in TextBox when user presses buttons "Prevoius" and "Next" in the Form. Commented May 9, 2015 at 14:20

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.