Huma Ali
Huma Ali

Reputation: 1809

How to cast a List<T> object into Text

I want to know if I can access an item of my List and assign it to a textbox?

public static List<Product> detailsList = new List<Product>();

Product is my class generated by using LINQ to SQL with fields Name,Code,Details i.e my List contains the items(Name,Code,Details). I want to access the value of the item Details from the list and assign it to a textbox . Something like:

txtDetails.Text = detailsList.Details.ToString()

Upvotes: 0

Views: 108

Answers (4)

RoteS
RoteS

Reputation: 1445

If you want the details of 1 item:

var detailsList = new List<TaskDto>();
// add items

// this if you know the corect index
txtDetails.Text = detailsList[0].Details;

// if you need to query for example for the item with the correct Id
txtDetails.Text = detailsList.FirstOrDefault(p => p.Id == 1).Details;

Upvotes: 4

Dovydas Šopa
Dovydas Šopa

Reputation: 2300

For all items:

var joinSymbol = ", ";
txtDetails.Text = string.Join(joinSymbol, detailsList.Select(detail => detail.Details));

For first item if Details:

txtDetails.Text = detailsList.FirstOrDefault()?.Details ?? string.Empty;

Upvotes: 0

Eric Lease
Eric Lease

Reputation: 4194

You can select first or default from the item based on some criteria, like the name.

public static List<Product> detailsList = new List<Product>();
var prod = detailsList.FirstOrDefault(p => p.Name == 'Ana');

if(prod != null) {
    txtDetails.Text = prod.Details;
}

Upvotes: 0

vantian
vantian

Reputation: 888

use string.Join() function.

txtDetails.Text = string.Join(",", detailsList.Select(e => e.Details)).ToList());

Upvotes: -1

Related Questions