Search code examples
c#listboxopenfiledialog

How do I show the filename in listbox but keep the relative path using openfiledialog?


I am making a program in which the user needs to load in multiple files. However, in the ListBox I need to show only file names of the files they loaded but still be able to use the files loaded. So I want to hide the full path. This is how I load a file into the ListBox now, but it shows the whole path:

private void browseBttn_Click(object sender, EventArgs e)
{
    OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
    OpenFileDialog1.Multiselect = true;
    OpenFileDialog1.Filter = "DLL Files|*.dll";
    OpenFileDialog1.Title = "Select a Dll File";
    if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        dllList.Items.AddRange(OpenFileDialog1.FileNames);
    }
}

Solution

  • // Set a global variable to hold all the selected files result
    List<String> fullFileName;
    
    // Browse button handler
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
            OpenFileDialog1.Multiselect = true;
            OpenFileDialog1.Filter = "DLL Files|*.dll";
            OpenFileDialog1.Title = "Seclect a Dll File";
            if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // put the selected result in the global variable
                fullFileName = new List<String>(OpenFileDialog1.FileNames);
    
                // add just the names to the listbox
                foreach (string fileName in fullFileName)
                {
                    dllList.Items.Add(fileName.Substring(fileName.LastIndexOf(@"\")+1));
                }
    
    
            }
        }
    
        // handle the selected change if you wish and get the full path from the selectedIndex.
        private void dllList_SelectedIndexChanged(object sender, EventArgs e)
        {
            // check to make sure there is a selected item
            if (dllList.SelectedIndex > -1)
            {
                string fullPath = fullFileName[dllList.SelectedIndex];
    
                // remove the item from the list
                fullFileName.RemoveAt(dllList.SelectedIndex);
                dllList.Items.Remove(dllList.SelectedItem);
            }
        }