如何从列表框中删除所选项目

时间:2017-09-11 09:01:19

标签: c# wpf mvvm-light

我在下面创建了一个DeleteSlectedItemListBox方法,该方法的代码在单击删除按钮时删除了列表框中的选定项目。然而,它似乎不起作用。

代码必须删除列表框以及文本文件中的内容。 我该怎么做?

 private void DeleteSelectedItemListBox()
 {
    DataTable dt = new DataTable();
    string FileName = (@"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
    StreamReader streamReader = new StreamReader(FileName);
    string line = "";
    int Counter = -1;

    while ((line = streamReader.ReadLine()) != null)
    {
        foreach (var item in line)
        {
            if (item.ToString() == SelectedItem.ToString())
            {
                Counter--;
                dt.Clear();
                ListBox.Remove(line);
            }           
        }       
    }
}

2 个答案:

答案 0 :(得分:0)

  while (listBox1.SelectedItems.Count > 0)
  {
    var index = listBox1.Items.IndexOf(listBox1.SelectedItem);
    listBox1.Items.RemoveAt(index);
    RemoveTextLine(index);
  }

private void RemoveTextLine(int index){

  using(var sr = new StreamReader("C:\Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text"))
  using(var sw = new StreamWriter("C:\Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\temp.text"))
  {
   int line=0;
   while((sr.ReadLine()) != null)
   {
      if(line != index)
      sw.WriteLine(line);
      line ++;
   }
 }

  File.Delete("Personal.txt");
  File.Move(tempFile, "Personal.txt");
}

试试这个

答案 1 :(得分:0)

如果您使用的是MVVM模式,则可以绑定XAML所选项目和ObservableCollention列表。 <ListBox ItemsSource="{Binding YourList}" SelectedItems="{Binding YourSelectedItem}"></ListBox> 然后在您的删除方法中,您可以尝试:

private void DeleteSelectedItemListBox()
{    
    var deletingNumber = YourList.IndexOf(YourSelectedItem);
    var allLines = File.ReadAllLines(path).ToList();
    allLines.RemoveAt(deletingNumber);
    File.WriteAllLines(path,allLines.ToArray());
}