ListViewItemCollection
does not implement the common ICollection<T>
or IEnumerable<T>
interfaces, so the compiler cannot guess the type of search in the Items
collection. Therefore, why you should explicitly specify a foreach
to iterate over a collection of type ListViewItem
instead of using var
.
Thus, the following code works:
var myPlayList = axWindowsMediaPlayer1.playlistCollection.newPlaylist("MyPlayList"); foreach (ListViewItem media in listView1.Items) { var mediaItem = axWindowsMediaPlayer1.newMedia(media.Text); myPlayList.appendItem(mediaItem); } axWindowsMediaPlayer1.currentPlaylist = myPlayList;
When you repeat the listView1.Items
loop in the foreach
using an implicitly typed variable ( var
), then media
treated as an object
. Therefore, when you call ToString()
, you actually call it on ListViewItem
. Which, like many other .NET classes, ListViewItem
, overrides the System.Object.ToString()
method. Which looks like this:
public override string ToString() { return "ListViewItem: {" + this.Text + "}"; }
Therefore, what happens when you use foreach (var media in listView1.Items)
and call axWindowsMediaPlayer1.newMedia(media.ToString())
, you actually call axWindowsMediaPlayer1.newMedia("ListViewItem: { C:\\Users\\...\\file.mp3 }";)
, which obviously does not work.
However, you can use var
successfully by listing each item you iterate over in the ListViewItem
, as in the following code.
foreach (var media in listView1.Items) { var fileLocation = (ListViewItem)media;
But I think this is primarily striking about using var
.
source share