How to format the name of an item in a listbox?

5

I'm having a project where I have to upload files over a network to a server.

WhenIclickthe"add" button it opens a box for the person to select the files they want to send and adds them to a list that stores objects of type "File".

So far so good, but the name is appearing even in the image. How do I get the file name to appear?

    
asked by anonymous 19.05.2016 / 00:45

3 answers

5

One way to do this is by redefining the ToString method of the class.

public override string ToString() {
    return "Meu texto aqui";
}

Another assumption is to set a value to DisplayMember . This property gets the name of a property defined in the class to display as text.

ListBox1.DisplayMember = "MeuCampoComTexto";
    
19.05.2016 / 09:11
5

Use this function to return the name of the formatted file:

string formatarItem(string item) {
    return System.IO.Path.GetFileNameWithoutExtension(item).Replace("_", " ");
}

Then, to add to the list, call the function like this:

ListBox1.Items.Add(formatarItem(arquivo));
    
19.05.2016 / 04:24
4

In order for the name of the selected files to be listed in the control list , I implemented the code below.

Notice that MultiSelect allows the return of a collection that can be obtained by FileNames and inserted immediately by Items.AddRange " of list .

ofd1.Title = "Selecione os arquivos";
ofd1.MultiSelect = true;
ofd1.InitialDirectory = @"C:\";

DialogResult dr = ofd1.ShowDialog();

// Se OK - Insere todos os arquivos selecionados pelo usuário no listbox
if (dr == System.Windows.Forms.DialogResult.OK)   
    listArquivos.Items.AddRange(ofd1.FileNames);
    
20.05.2016 / 05:34