Tania Akter Tania Akter - 3 months ago 18
C# Question

How to remove item listbox & dictionary on click?

I created a listbox with dictionary.

But I want to remove item listbox & dictionary at once on click.

This is my listbox

Code:

Xaml:

<ListBox x:Name="ListBoxPlayList" SelectionMode="Extended"/>

<Button x:Name="addbtn" Margin="2,5,41,5" Click="addbtn_Click" />

<Button x:Name="removebtn" Click="removebtn_Click" />


Xaml.cs:

public Dictionary<string, string> fileDictionary = new Dictionary<string, string>();

private void addbtn_Click(object sender, RoutedEventArgs e)
{
var listCount = ListBoxPlayList.Items.Count;
Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.DefaultExt = ".mp3";
ofd.Filter = "All|*.*";
ofd.Multiselect = true;
Nullable<bool> result = ofd.ShowDialog();
if (result == true)
{
for (int i = 0; i < ofd.FileNames.Length; i++)
{
var filePath = ofd.FileNames[i];
var fileName = System.IO.Path.GetFileName(filePath);
fileDictionary.Add(fileName, filePath);
ListBoxPlayList.Items.Add(fileName);
}
ListBoxPlayList.SelectedIndex = listCount;
}
}


I am trying by this code:

But item remove from Dictionary but not remove from listbox when I click the remove button.

private void remove(object sender, RoutedEventArgs e)
{

var itemsToRemove = listbox4.SelectedItems;
foreach (var item in itemsToRemove)
{
fileDictionary.Remove(item.ToString());
listbox4.Items.Remove(item);
}

}


Note:

I want to remove item from listbox & fileDictionary at once.

& Without the playing item.

This code worked when I don't use dictionary.

private void removebtn_Click(object sender, RoutedEventArgs e)
{
object[] itemsToRemove = new object[ListBoxPlayList.SelectedItems.Count];
ListBoxPlayList.SelectedItems.CopyTo(itemsToRemove, 0);

foreach (object item in itemsToRemove)
{
if (mediaelement.Source != new Uri(item.ToString())) //MediaPlayer source
ListBoxPlayList.Items.Remove(item);

}


}

Question:

How can I remove selected items from listbox & dictionary on click and ignore remove item which is playing on my mediaelement??

Answer

Could you please check with this code? Without getting the entire code, I cant test it.

private void removebtn_Click(object sender, RoutedEventArgs e)
{
    object[] itemsToRemove = new object[ListBoxPlayList.SelectedItems.Count];
    ListBoxPlayList.SelectedItems.CopyTo(itemsToRemove, 0);
    foreach (var item in itemsToRemove)
    {
        fileDictionary.Remove(item.ToString());
        ListBoxPlayList.Items.Remove(item);
    }
}
Comments