Andreas Jung

Andreas Jung

  • 1.6k
  • 9
  • 707

show all elements of a list class

Jun 5 2024 4:12 PM

Hello, I learn now DataBindingBasics. I want to print all List<T> Class elements to a textbox

In form1.cs I have the following code:

        List<Class2> raceCarDrivers = new List<Class2>();

        public Form1()
        {
            InitializeComponent();

            //Populate list data source with data items
            this.raceCarDrivers.Add(new Class2("M. Schumacher", 500));
            this.raceCarDrivers.Add(new Class2("R. Schumacher", 501));
            this.raceCarDrivers.Add(new Class2("A. Senna", 502));
            this.raceCarDrivers.Add(new Class2("A. Prost", 503));
            this.raceCarDrivers.Add(new Class2("F. Schoebel", 504));
        }
        some code...
        
         private void button5_Click(object sender, EventArgs e)
        {
            foreach (Class2 p in raceCarDrivers)
            {
                textBox1.Text = p.Name + " " + (p.Wins).ToString() + ";\r\n"; 
            }

        } 

After I click the button 5 the textbox shows me only one (the last) racecardriver with his wins. But i Want to see a list of all of them.

the class2.cs is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace DataBindingBasics01
{
    class Class2
    {
        string name;
        int wins;

        public Class2(string name, int wins)
        {
            this.name = name;
            this.wins = wins;
        }

        //event
        public event PropertyChangedEventHandler PropertyChanged;

        public string Name
        {
            get { return this.name; }
            set { this.name = value;
            this.OnPropertyChanged("Name");
            }
        }
        public int Wins
        {
            get { return this.wins; }
            set { this.wins = value;
            this.OnPropertyChanged("Wins");
            }
        }

        //helper from the event
        void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                //this = object sender
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

 


Answers (1)