I fill a list from a OpenFileDialog
and put it in "file" and then put it in the list like this:
foreach (string file in selectedFiles)
{
ListBoxItem lstItem = new ListBoxItem();
lstItem.Content = file; //File es la cadena de la URL
miLista.Items.Add(lstItem);
}
What I assign to the ListBox
are URL
type
c:\user\paco\image1.jpg
c:\user\paco\image2.jpg
So far so good, but now I need to loop through that ListBox
and put its Items into aString[]
String[] matriz = new String[miLista.Items.Count];
foreach (Object index in miLista.Items)
{
matriz = index.ToString().Split();
}
In this way, what gets me in each index of the string[]
is the following:
System.Windows.Controls.ListBoxItem: c:\user\cucumber\image1.jpg System.Windows.Controls.ListBoxItem: c:\user\cucumber\image2.jpg System.Windows.Controls.ListBoxItem: c:\user\cucumber \image3.jpg
What I need is only the URL
and that it does not return the Type and the Value, I need to put String[]
only the value in it.
I fill the ListBox
like this:
OpenFileDialog myFD = new OpenFileDialog();
myFD.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
myFD.Multiselect = true;
myFD.Title = "Seleccione uno o más archivos";
myFD.Filter = "Archivos imagen (*.jpg),(*.jpeg),(*.gif),(*.png)|*.jpg;*.jpeg;*.gif;*.png";
Nullable<bool> result = myFD.ShowDialog();
if (result == true)
{
string[] selectedFiles = myFD.FileNames; // La propiedad FileNames (o FileName) almacena la ruta, nombre y extensión.
foreach (string file in selectedFiles)
{
miLista.Items.Add(file);
}
archivo.set_listaReproduccion(selectedFiles);
archivo.grabar();
}
The problem you have is in this piece of code:
One solution would be to replace this line and use the suggestions we gave you earlier:
By
But if you need it
lstItem
to stay in the collectionlistbox.Items
then all you have to do is cast.Assuming you load your listbox like this, you shouldn't have any casting problems:
Note that
FileNames
it is already aString[]
practically you do not need to do neither thecopy
nor thefor
only assign it:But anyway I'm going to leave below ways to do it so it can be useful to other people.
The simplest option is:
But you can also do it using a loop
for
instead of theforeach
You can try using:
And then:
With this you directly have an array
string
with all the values.EDIT: I clarify that
Cast<string>()
it should not be necessary since we are adding items of typestring
to list.If the above doesn't work for you, you can try combining Alan's answer and this one:
This is supposed to work, since you have elements of type string inside
ListBox.Items
Sometimes the order of the instructions can be wrong, but it can work either way.
Here I leave you the response from SO where I found something similar, greetings!