Mr Riksson
Mr Riksson

Reputation: 560

Printing items from Class based List

I have a List based on my class:

class Vara
{
    public int streckKod { get; set; }
    public string artNamn { get; set; }
}

and the list looks like this:

List<Vara> minaVaror = new List<Vara>();

I'm adding to the list by this line:

minaVaror.Add(new Vara() {streckKod = inputBox1, artNamn = textBox2.Text });

But my problem is when I want to print an item from the lest to a textbox, let's say texBox3,

How can I print an item from the list as every item now contains 2 variables, and also would I be able to only print one of the 2 variables? Say if I just wanted to print the arNamn variable.

Upvotes: 0

Views: 1024

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81253

You can explicitly set the text like this -

TextBox textBox = new TextBox();
textBox.Text = minaVaror[0].artNamn;

Or more specifically if you don't want to update the text everywhere, you can override ToString() method in your class and return variable which you want to print -

class Vara
{
    public int streckKod { get; set; }
    public string artNamn { get; set; }

    public override ToString()
    {
       return artNamn;
    }
}

This way you don't have to worry about changing variable name everywhere in case you want to replace it with other variable in future. Only need to update in ToString() method.

TextBox textBox = new TextBox();
textBox.Text = minaVaror[0];

Upvotes: 1

Aage
Aage

Reputation: 6252

Something like this:

var textBox = new TextBox();
textBox.Text = minaVaror[0].artNamn;

Upvotes: 2

Related Questions