Talisson Junior
Talisson Junior

Reputation: 79

Format issue in Listbox

I want to show on my listbox this type of format:

"File name Size";

 foreach (string filePath in filePaths)
        {
            BarraDeProgresso.Visible = true;
                PegarMeuFicheiro = filePath;
// here is where im tryng to do it. but isn´tworking as i expected.
            lbMostrarItems.Items.Add(String.Format("{0, 5} {1, 30}",PegarMeuFicheiro.Substring(9 + nome.Length + 20, PegarMeuFicheiro.Length - (9 + nome.Length + 20)),"Size"));
            //lbMostrarItems.SelectedIndex = lbMostrarItems.Items.Count - 1;

        }

enter image description here

What can I do to make it all align on the right?

Upvotes: 0

Views: 186

Answers (2)

Alexander Petrov
Alexander Petrov

Reputation: 14231

You can manually draw item in the ListBox.
Example:

public Form1()
{
    //InitializeComponent();
    this.Width = 500;

    var listBox = new ListBox { Parent = this, Width = 400, Height = 250 };
    listBox.DrawMode = DrawMode.OwnerDrawFixed;

    var files = new DirectoryInfo(".").GetFiles();
    listBox.DataSource = files;

    listBox.DrawItem += (o, e) =>
    {
        e.Graphics.DrawString(files[e.Index].Name, listBox.Font, Brushes.Black, e.Bounds);

        var length = files[e.Index].Length.ToString();
        var size = e.Graphics.MeasureString(length, listBox.Font);

        e.Graphics.DrawString(length, listBox.Font,
            Brushes.Black, e.Bounds.Width - size.Width, e.Bounds.Y);
    };
}

enter image description here

Upvotes: 0

Dayan
Dayan

Reputation: 8031

Make use of the ListView control instead which allows for columns and many other features.

First add the control, then select it and go to the control's property and change the View to Details. This will allow you to see a list with resizable column names.

Next, create two columns (One for the file name and the other for the file size) or whatever it may be in your case. To do this, on the properties window go to Columns and click it to get the dialog window which will allow you to add columns.

Finally, here is some sample code on how to use ListView.

private void Form1_Load(object sender, EventArgs e)
{
    var fileListForExample = Directory.GetFiles(@"C:\");
    foreach (var item in fileListForExample)
    {
        FileInfo fileInfo = new FileInfo(item);
        var lstItem = new ListViewItem(Path.GetFileName(item));
        lstItem.SubItems.Add(fileInfo.Length.ToString());

        var itemAdded = listView1.Items.Add(lstItem);
    }
}

enter image description here


enter image description here

Upvotes: 2

Related Questions