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

Asked

Viewed 269 times

5

I have a project where I have to send files over the network to a server.

inserir a descrição da imagem aqui

When I click on the "add" button a box opens for the person to select the files they want to send and adds to a list that stores objects of type "File".

So far so good, but the name is appearing like in the image. As I do so that the name of the file appears?

3 answers

5

Use this function to return the formatted file name:

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

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

ListBox1.Items.Add(formatarItem(arquivo));

5


One of the ways to do this is by redefening the method ToString class.

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

Another hypothesis is to define a value for DisplayMember. This property takes the name of a property in the class to display as text.

ListBox1.DisplayMember = "MeuCampoComTexto";
  • Thanks man! Yours was the simplest and what worked was this "Listbox1.Displaymember" that worked. I put the attribute "name" in it and the name of the file appeared. Thanks to the others also because I implemented it here and it became more beautiful.

4

So that the name of the selected files are listed in control list, implemented the code below.

Note that the 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.