I'm trying to learn List<> in C#. I made a test program that takes the result of three textboxes and inputs it in a multiline textbox, after I put them in a list (to later save the list to file).
Here is my class declaration:
public class Film
{
public Film (string Num, string Title, string Categ)
{
this.Numero = Num;
this.Titre = Title;
this.Categorie = Categ;
}
public string Numero;
public string Titre;
public string Categorie;
}
Now I instantiate the list:
List<Film> ListeFilms = new List<Film>();
And here is my event:
private void btSaveMovie_Click(object sender, EventArgs e)
{
var MyMovie = new Film(txtNum.Text, txtTitre.Text, cbCateg.Text);
ListeFilms.Add(MyMovie);
foreach (Film x in ListeFilms)
{
txtAffichage.AppendText(x.ToString());
}
}
Now when I run, all that is written in the text box is:
test_1.Form1+Film
What did I do wrong?
You have to override the ToString() method in the Film class declaration.Otherwise it returns the type name.
Example:
public class Film
{
public Film(string Num, string Title, string Categ)
{
this.Numero = Num;
this.Titre = Title;
this.Categorie = Categ;
}
public string Numero;
public string Titre;
public string Categorie;
public override string ToString()
{
return Numero.ToString() + " " + Titre.ToString() + " " + Categorie.ToString();
}
}
You just have to concatenate the three fields into the AppendText function:
private void btSaveMovie_Click(object sender, EventArgs e)
{
var MyMovie = new Film(txtNum.Text, txtTitre.Text, cbCateg.Text);
ListeFilms.Add(MyMovie);
foreach (Film x in ListeFilms)
{
txtAffichage.AppendText(x.Numero + " - " + x.Titre + "- " + x.Categorie));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.