When I'm get .mp3 file without path but I couldn't play Uri got some errors. My codes;
private void listbox2_Drop(object sender, DragEventArgs e)
{
try
{
string[] a = (string[])(e.Data.GetData(DataFormats.FileDrop, false));
foreach (var names in a)
{
FileInfo fileInfo = new FileInfo(names);
if (fileInfo.Extension == ".MP3" ||fileInfo.Extension == ".mp3")
{
listbox2.Items.Add( fileInfo.Name);
}
}
}
catch (Exception)
{}
}
private void listbox2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
object listboxİtems = listbox2.SelectedItem;
if (listboxİtems != null)
{
media2.Source = new Uri(listboxİtems.ToString(), UriKind.Relative); // I'm getting erors here
media2.Play();
}
}
he got error at media2.Source that listboxItems.ToString() string is unable to play
Just add the full FileInfo object to your Items.
Then you have the full object to build your Uri with FullPath or DirectoryName and Name.
Finally, define your ListBox.ItemTemplate to something that suits your needs (like a TextBlock bound to the Name property)
Here goes some of the requested code :
private void listbox2_Drop(object sender, DragEventArgs e)
{
try
{
string[] a = (string[])(e.Data.GetData(DataFormats.FileDrop, false));
foreach (var names in a)
{
FileInfo fileInfo = new FileInfo(names);
if (fileInfo.Extension == ".MP3" ||fileInfo.Extension == ".mp3")
{
listbox2.Items.Add(fileInfo); //store the full FileInfo in your Items, not just the Name property
}
}
}
catch (Exception)
{}
}
private void listbox2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
FileInfo listboxItem = listbox2.SelectedItem as FileInfo; //cast the SelectedItem to the FileInfo type
if (listboxItem != null)
{
media2.Open(new Uri(listboxItem.FullPath, UriKind.RelativeOrAbsolute)); // if I remember well, Source is Read-Only, use Open instead
media2.Play();
}
}
And the suggested XAML for the ListBox :
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Related
I have 2 list views and I'm trying to drag an item from one to the other.
The typeof item is a storagefile.
private async void ListA_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
List<IStorageItem> files = new List<IStorageItem>();
StorageFile file = e.Items;
files.Add(file);
e.Data.SetStorageItems(files);
}
private void ListC_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
}
private async void ListC_Drop(object sender, DragEventArgs e)
{
//if (e.DataView.Contains(StandardDataFormats.StorageItems))
//{
// var items = await e.DataView.GetStorageItemsAsync();
// if (items.Count > 0)
// {
// var storageFile = items[0] as StorageFile;
// ListC.Items.Add(storageFile);
// }
// }
}
I've tried everything I can think of to drop the storage file into the other listview and show the display name... All I've been able to display are types and stuff.
Can anyone help me?
I've solved it after hours or trying.
private async void ListA_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
//f.MessageBox(e.Items.First().GetType().ToString());
try
{
List<IStorageItem> files = new List<IStorageItem>();
StorageFile file = e.Items.First() as StorageFile;
files.Add(file);
e.Data.SetStorageItems(files);
//e.Data.SetData(StandardDataFormats.Text, e.Items.);
}catch(Exception ex)
{
f.MessageBox(ex.Message);
}
}
private async void ListC_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
//IReadOnlyList<IStorageItem> files = await e.DataView.GetStorageItemsAsync();
}
private async void ListC_Drop(object sender, DragEventArgs e)
{
try
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
if (items.Count > 0)
{
var storageFile = items[0] as StorageFile;
ListC.Items.Add(storageFile.Name);
}
}
}catch
{
f.MessageBox("nope");
}
I am populating a listbox with a file. This can be done by two methods, the open file dialog command initiated by a button press and a drag/drop action into the listbox. I want to pass on the file path (for the file in the listbox) to other areas of my code, for example the DataContext that reads the file in the listbox. Basically I want the file path to automatically update when the listbox is populated. I am new to C# so sorry if I haven't explained myself properly or provided enough information. The code for populating my listbox (named FilePathBox) and the 'Run' button is as follows:
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
//openFileDialog.Multiselect = true;
openFileDialog.Filter = "Csv files(*.Csv)|*.Csv|All files(*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog())
{
FilePathBox.Items.Clear();
foreach (string filename in openFileDialog.FileNames)
{
ListBoxItem selectedFile = new ListBoxItem();
selectedFile.Content = System.IO.Path.GetFileNameWithoutExtension(filename);
selectedFile.ToolTip = filename;
FilePathBox.Items.Add(selectedFile);
}
}
}
private void FilesDropped(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
FilePathBox.Items.Clear();
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
ListBoxItem fileItem = new ListBoxItem();
fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
fileItem.ToolTip = droppedFilePath;
FilePathBox.Items.Add(fileItem);
}
}
}
private void RunButton_Click(object sender, RoutedEventArgs e)
{
DataContext = OldNewService.ReadFile(#"C:\Users\Documents\Lookup Table.csv");
}
I added a comment, but I think what you need a way to get the selected file path when the RunButton is clicked, so just add this to your RunButton_Click method,
private void RunButton_Click(object sender, RoutedEventArgs e)
{
string selection = (string)FilePathBox.SelectedItem;
DataContext = OldNewService.ReadFile(selection);
}
I have code and i need add to treeview only (image files) or image files higlights by other color. Do you have any ideas ? I will like for every advice. I am adding for example Download Folder, in which i have some jpeg, some avi etc. I need images with other color or add just jpeg,png and other image files.
System.Windows.Forms.FolderBrowserDialog dlg = new System.Windows.Forms.FolderBrowserDialog();
Image img = new Image();
public MainWindow()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
dlg.Description = "Vyberte složku, kterou přidat";
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtbox1.Text = dlg.SelectedPath;
ListDirectory(treeView1, dlg.SelectedPath);
}
}
private void btn3_Click(object sender, RoutedEventArgs e)
{
TreeViewItem SelectedTreeViewItem = treeView1.SelectedItem as TreeViewItem;
string FileName = "";
if (SelectedTreeViewItem != null)
{
FileName = SelectedTreeViewItem.Header.ToString();
}
{
canvas1.Children.Remove(img);
img.Source = new BitmapImage(new Uri(dlg.SelectedPath + "\\" + FileName));
img.Width = 250;
img.Height = 185;
canvas1.Children.Add(img);
}
}
private void btn4_Click(object sender, RoutedEventArgs e)
{
canvas1.Children.Remove(img);
}
private void ListDirectory(TreeView treeView, string path)
{
treeView.Items.Clear();
var rootDirectoryInfo = new DirectoryInfo(path);
treeView.Items.Add(CreateDirectoryNode(rootDirectoryInfo));
}
private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeViewItem { Header = directoryInfo.Name };
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Items.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles())
directoryNode.Items.Add(new TreeViewItem { Header = file.Name});
return directoryNode;
}`
You can use LINQ to filter appropriate files:
private static TreeViewItem CreateDirectoryNode(DirectoryInfo directoryInfo)
{
var directoryNode = new TreeViewItem { Header = directoryInfo.Name };
foreach (var directory in directoryInfo.GetDirectories())
directoryNode.Items.Add(CreateDirectoryNode(directory));
foreach (var file in directoryInfo.GetFiles().Where(x=> x.Extension == ".jpg" || x.Extension == ".png"))
directoryNode.Items.Add(new TreeViewItem { Header = file.Name });
return directoryNode;
}
Following code is responsible for selection only pictures:
directoryInfo.GetFiles().Where(x=> x.Extension == ".jpg" || x.Extension == ".png")
Is it possible to display a listbox content, with only certain files that have a certain format? like BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff only these files with these extensions that I want to display within the lstFiles listbox.
I have tried,
lstFiles.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff";
But this did not work, is it possible?
EDIT:
I have three joint listboxes to display the system drive, folders and its content
private void lstDrive_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFolders.Items.Clear();
try
{
DriveInfo drive = (DriveInfo)lstDrive.SelectedItem;
foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
lstFolders.Items.Add(dirInfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
lstFiles.Items.Add(fi);
}
private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(((FileInfo)lstFiles.SelectedItem).FullName);
}
private int lastIndex = 0;
private void lstFiles_KeyUp(object sender, KeyEventArgs e)
{
if (lstFiles.SelectedIndex == lastIndex)
{
if (e.KeyCode == Keys.Up)
{
lstFiles.SelectedIndex = lstFiles.Items.Count - 1;
}
if (e.KeyCode == Keys.Down)
{
lstFiles.SelectedIndex = 0;
}
}
lastIndex = lstFiles.SelectedIndex;
}
}
}
You are population the listbox yourself using a FileInfo object. FileInfo has a property Extension. You can use that one for filtering:
private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
switch(fi.Extension.ToUpperInvariant())
{
case ".BMP":
case ".JPG":
...
lstFiles.Items.Add(fi);
break;
}
}
Ok, I personaly have no idea nor have ever heard of using "filter" on a list box. Why don't you just add the items you want when you have the list?
lstFiles.Items.Clear();
List<string> allowedExtensions = new List<string>() {".jpg", ".png", ".gif"};
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles().Where((x)=>allowedExtensions.Contains(x)))
{
lstFiles.Items.Add(fi);
}
I know what's wrong, I don't know how to fix it.
I get a
NullReferenceException: Object reference not set to an instance of an object.
I get this error because I have a populated ListBox, when you select a file name in the ListBox the contents of that file are then displayed in a textbox.
Now, I have a depopulate button that clears all the files from the ListBox, if a file is selected, then I get the error.
I want to be able to click the depopulate button and clear both boxes.
The code:
private void DE_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
myScaleTransform2.ScaleX = myScaleTransform2.ScaleX * .9833333333333333333333333333333333333333333333333333333333;
myScaleTransform2.ScaleY = myScaleTransform2.ScaleY * .9833333333333333333333333333333333333333333333333333333333;
lbz.Items.Clear();
}
private void lbz_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
tb1.Text = File.ReadAllText(lbz.SelectedItem.ToString());
}
you will have to check, whether SelectedItem is actually set:
private void lbz_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if( lbz.SelectedItem != null ){
tb1.Text = File.ReadAllText(lbz.SelectedItem.ToString());
} else {
tb1.Text = "No File Selected";
}
}
private void lbz_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if( lbz.SelectedItem != null ){
if(File.Exist(lbz.SelectedItem.ToString())){
tb1.Text = File.ReadAllText(lbz.SelectedItem.ToString());
}
else
{
tb1.Text = "File is not exist in the selected Path";
}
} else {
tb1.Text = "No File Selected";
}
}
Please check weather your list item contain file path or not?