I have a combobox with items(paths of opened files with opendialog).
Screenshot http://screenshotuploader.com/i/01/0k8n94fka.png
How to show only files name in combobx preview?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Title = "Выбрать фаил для загрузки";
openFileDialog1.InitialDirectory = System.Environment.CurrentDirectory;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
comboBox1.Items.Add(file);
}
}
I think you need a custom class, which looks like this:
public class ComboBoxItem
{
public string Display{get;set;}
public string Value{get;set;}
public override ToString()
{
return this.Display.ToString();
}
}
Can't see how any of the other answers here would work so thought i'd help out
Just use SafeFileNames instead of FileNames,
SafeFileNames: Gets an array of file names and extensions for all the selected files in the dialog box. The file names do not include the path.
e.g.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
foreach (String file in openFileDialog1.SafeFileNames)
{
comboBox1.Items.Add(file);
}
}
Will give you the desired result.
r u binding the combobox with the entire path..??
Just try this code to extract filename
Path.GetFileName(YourPath);
Add the resultant string to combobox
Related
I have a button that opens a file browser and select multiple files, then adds them to a ListView.
How can I force the Browser Dialog Box to always sort the files by name before being added to the ListView?
Sometimes windows defaults to Date Modified or another sorting method besides Name.
Note: I have full file paths in a List, and just file names in the ListView.
private void btnInput_Click(object sender, RoutedEventArgs e)
{
// Open Select File Window
Microsoft.Win32.OpenFileDialog selectFiles = new Microsoft.Win32.OpenFileDialog();
selectFiles.Multiselect = true;
// Process Dialog Box
Nullable<bool> result = selectFiles.ShowDialog();
if (result == true)
{
// Add Path+Filename to List
foreach (String file in selectFiles.FileNames)
{
lstFilesPaths.Add(file);
}
// Add List Filename to ListView
lsvFiles.Items.Clear();
foreach (String name in fileList)
{
lsvFileNames.Items.Add(Path.GetFileName(name));
}
}
}
The filebrowser itself won't sort its results by filename, you will need to do that before using them.
Given lstFilesPaths is a List of strings you're saving the selected file paths to for use elsewhere, try this to sort the list by file name adding:
foreach (var name in lstFilesPaths.Select(f => Path.GetFileName(f)).OrderBy(s => s))
{
lsvFileNames.Items.Add(name);
}
Or, if you'd like both your list of file paths and the list view of file names sorted, try this:
// Add Path+Filename to List
lstFilesPaths.AddRange(selectFiles.FileNames.OrderBy(f => Path.GetFileName(f)));
// Add List Filename to ListView
lsvFiles.Items.Clear();
foreach (var name in lstFilesPaths.Select(f => Path.GetFileName(f)))
{
lsvFileNames.Items.Add(name);
}
try changing to:
lstFilePaths.AddRange(selectFiles.FileNames.OrderBy(x => x))
lsvFileNames.Items.Clear();
lstFilePaths.ForEach(x => lsvFileNames.Items.Add(Path.GetFileName(x)));
I'm doing a text editor. How do I display a list of the last opened files in the RichTextBox in ListView? You can also click on the ListView string and open the file. Something like the history of opening files. Files are opened using Button (the code below).
private void buttonOpen_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Rich Text Format | *.rtf";
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(ofd.FileName);
}
else
{
}
}
The easiest way i have done this was store all opened files within a settings string and store all recently opened files within that string with a delimiter like \n(i use this because you cant include it in a fie name so no errors are thrown).
For example, the settings string is stored like this
"C:\my file1\nC:\myFile2\nC:\my file 3"
And when adding a new file to the list
MyApp.Properties.Settings.recents = MyApp.Properties.Settings.recents + "\n" + ofd.FileName;
MyApp.Properties.Settings.Default.Save();
you then split that and use a forloop for each occurance to generate a new listview item like this
string[] recentFiles = MyApp.Properties.Settings.recents.split('\n');
foreach (string recentItem in recentFiles) { MyListView.add(recentItem); }
I have a multi-select OpenFileDialog box (named GetFiles) that loops through all the selected files and displays their path in a listbox. Problem is, when all the files are selected and added, it displays the same filename. Here is all the code:
if (GetFile.ShowDialog() == DialogResult.OK)
foreach (string filename in GetFile.FileNames)
{
FileNameList.Items.Add(GetFile.FileName);
}
I feel like there is something really simple that I'm missing....any help will be greatly appreciated
Yes, you are adding the same filename each time using GetFile.FileName. You need to use your variable filename:
if (GetFile.ShowDialog() == DialogResult.OK)
foreach (string filename in GetFile.FileNames)
{
FileNameList.Items.Add(filename);
}
Yes, you're using GetFile.FileName when adding to the list rather than the enumerated value filename.
Try this instead:
if (GetFile.ShowDialog() == DialogResult.OK) {
foreach (string filename in GetFile.FileNames) {
FileNameList.Items.Add(filename);
}
}
I want to mimic the functionality of the following image using Visual C#:
This I know is not a textbox or a combobox or a richtext (Maybe).
I managed to get the add function, where I get directories and I can select them:
private void button8_Click(object sender, EventArgs e)
{
this.folderBrowserDialog1.ShowNewFolderButton = false;
this.folderBrowserDialog1.RootFolder = System.Environment.SpecialFolder.MyComputer;
DialogResult result = this.folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
// the code here will be executed if the user selects a folder
string path = this.folderBrowserDialog1.SelectedPath;
}
}
How do I list them like in the image, should I write it to an ini file, or XML file, and then if so how do I list it in the box as shown.
I also need to detect the OS and have few default folders in the list.
Not quite sure what you want, but the image shows a list with a string and bool value. So you can use something like this:
public class DirOptions
{
string Path = string.Empty;
bool IncludeSubDirs = false;
}
Then you can store your data inside a List<>:
var list = new List<DirOptions>();
To detect OS:
Please see this question Get OS Version / Friendly Name in C#
Background: I'm developing a WinForms application using C# with an OpenFileDialog and FileBrowserDialog that is supposed to:
Enable selection of multiple xls files.
After selection is made, Display selected xlsx filenames in textbox
Copy the selected files to a separate directory Consolidated
Show results in logging window on the bottom of the winForm App
How do you recommend to fix any of the following Errors in Debugging:
After selecting the files from the FileBrowserDialog, another FileBrowserDialog box comes up
Only 1 of the files selected shows up in the textbox. There's not enough room to display all files b/c the file paths are so long. Would it be possible to just display the filename without the full path? Is there a better way for confirming the MultiSelect worked in a WinForm besides displaying the selected files in a textbox that you recommend?
Hitting the Consolidate button does not copy the selected files to the consolidated directory or display the correct log files.
I get the following in the Logging Window: "Source Files: System.String[]"
Here's my code:
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFilesList = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
{
using (myStream)
{
Log("Source Files: " + sourceFilesList.FileNames);
}
} // ends if
} // ends try
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
} // ends if (sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
} // ends public void sourceFiles_Click
private void consolidateButton_Execute_Click(object sender, EventArgs e)
{
string consolidatedFolder = targetFolderBrowserDialog.SelectedPath;
foreach (String file in sourceFileOpenFileDialog.FileNames)
{
try
{
// Copy each selected xlsx files into the specified TargetFolder
System.IO.File.Copy(sourceFileOpenFileDialog.FileName, consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
Log("File" + sourceFileOpenFileDialog.FileName + " has been copied to " + consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
}
} // ends foreach loop
} // ends void consolidateButton_Execute_Click
I will give +1 up-votes for any helpful answers!
Thanks for looking!
Update: Updated code w/ a foreach (string FileName in sourceFilesList.FileNames) loop and a listbox control, still having problems w/ filebrowser loading 2x, and the "Source Files: System.String[]" message
Your code snippet doesn't match your question very well, there's no sign of you displaying the FolderBrowserDialog. There is an obvious mistake in the File.Copy() call, you pass sourceFileOpenFileDialog.FileName instead of file.
Check this answer for a way to display path names in a limited amount of space:
using System;
using System.ComponentModel;
using System.Windows.Forms;
class PathLabel : Label
{
[Browsable(false)]
public override bool AutoSize
{
get { return base.AutoSize; }
set { base.AutoSize = false; }
}
protected override void OnPaint(PaintEventArgs e)
{
TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.PathEllipsis;
TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, flags);
}
}
To get only file name from file path use Path.GetFileName(...).
To check if multiple files were selected, you can just check openFileDialog.FileNames Length property - it's an array.
Fixed Logging Window Message: "Source Files: System.String[]" by adding:
foreach (string FileName in sourceFilesList.FileNames)
{
sourceFilesList.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFilesList.FileNames[i]);
i++;
}
// under if ((myStream = sourceFileOpenFileDialog.OpenFile()) != null)
Fixed 2 FileBrowserDialog boxes coming up when Selecting files by:
if ((myStream = sourceFilesList.OpenFile()) != null)
// deleted duplicate line