atrljoe
atrljoe

Reputation: 8151

Collection Variable Question

Lets say that I have a generic collection in the string format. I want to extra the values to a label how would I go about doing that ive tried a few things ive read on here but cant seem to get it to work.

List<string> listcollection= new List<string>();

....Populate Collection Here....

MsgLabel.Text = Controls[string.Format(("MyInts: {0}", listcollection[1].Text));

Any help would be awesome.

Thanks.

Upvotes: 0

Views: 682

Answers (3)

S&#246;ren
S&#246;ren

Reputation: 2741

If you want to combine all the strings (and it seems to me like you wanna do that), you can do something like:

List<string> listcollection = new List<string>();
string myText = string.Empty;
for (int i = 0; i < listcollection.Count; i++) {
   myText += ("string no. " + (i - 1).ToString() + ": " + listcollection[i] + Environment.NewLine);
}
MsgLabel.Text = myText;

or use , instead of Environment.NewLine if you want to split it by ,

EDIT: See the comment of Lasse V. Karlsen for a quicker solution. Thanks for the hint!

Upvotes: 0

wałdis iljuczonok
wałdis iljuczonok

Reputation: 662

If you are creating generic collection of strings you should not call "Text" property collection[idx].Text. Just use .Join or extract particular element from the collection.

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391734

There's multiple ways to understand your question:

  • You want to extract the 2nd value and place it in the label, as shown in the example
  • You want to combine all the values into a list (MyInts is plural)

Extract 2nd value

MsgLabel.Text = string.Format("MyInts: {0}", listcollection[1]);

To combine them

You're probably looking for string.Join.

This would work with the example you've posted:

MsgLabel.Text = string.Format("MyInts: {0}", string.Join(", ", listcollection));

That code requires .NET 4.0, otherwise string.Join requires an array, so if you're not on 4.0, the following code is what you need:

MsgLabel.Text = string.Format("MyInts: {0}", string.Join(", ", listcollection.ToArray()));

Upvotes: 4

Related Questions