vs2010noob
vs2010noob

Reputation: 213

Deleting Multiple Items from a ListBox; Update in XML

I use an XML file to store from and display the contents on a ListBox.

Here is an sample XML file;

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>
<Entry>
<Details>0</Details>
</Entry>
<Entry>
<Details>1</Details>
</Entry>
<Entry>
<Details>2</Details>
</Entry>
<Entry>
<Details>3</Details>
</Entry>
<Entry>
<Details>4</Details>
</Entry>
<Entry>
<Details>5</Details>
</Entry>
<Entry>
<Details>6</Details>
</Entry>
</Root>

Users can select the values on the ListBox (selection mode is MultiExtended) and delete them.

My problem is, well, it's better to show than to explain;

Selected Items --

Selected Items

After Pressing the Del key --

Deleted Items

Contents of the XML file are same as of ListBox.

The result is even more weird when I select all and press delete.

Am I doing something wrong ?

How to get the indexes of multiple items and handle them correctly ?

Here's my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows.Forms;

namespace XML_ListBox
{
    public partial class Form1 : Form
    {
        string path = "Test.xml";
        public Form1()
        {
            InitializeComponent();
            LoadFile();
        }

        private void LoadFile()
        {
            XDocument xdoc = XDocument.Load(path);
            foreach (var el in xdoc.Root.Elements())
            {
                listBox1.Items.Add(el.Element("Details").Value);
            }
        }

        private void OnDelete(object sender, KeyEventArgs e)
        {
            XElement root = XElement.Load(path);

            if (e.KeyCode == Keys.Delete)
            {
                foreach (Object index in listBox1.SelectedIndices)
                {
                    root.Elements("Entry").ElementAt((int)index).Remove();
                    listBox1.Items.RemoveAt((int)index);
                }

                root.Save(path);
            }
        }
    }
}

Upvotes: 1

Views: 1019

Answers (1)

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

Your code trys to delete items by indexes, but each time wnen you delete an item with the index X, the item with index X+1 will be moved to the index X. So each time when you delete the item with Index = 0 the item with Index 5 become to the Index 4.

You can try to sort indexes:

if (e.KeyCode == Keys.Delete)
{
  foreach (int index in listBox1.SelectedIndices.Cast<int>().OrderByDescending(i=>i))
  {
    root.Elements("Entry").ElementAt(index).Remove();
    listBox1.Items.RemoveAt(index);
  }

  root.Save(path);
}

But the preffered way to delete items is delete by Key value instead of the index value

Upvotes: 2

Related Questions