我使用XML文件来存储ListBox中的内容并在其上显示内容。
下面是一个示例XML文件;
<?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>用户可以选择ListBox上的值(选择模式为MultiExtended)并将其删除。
我的问题是,嗯,展示比解释更好;
所选项目--

按下Del键后--

XML文件的内容与ListBox的内容相同。
当我选择全部并按下delete时,结果更加奇怪。
我做错了什么吗?
如何获取多个项目的索引并正确处理?
下面是我的代码:
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);
}
}
}
}发布于 2012-05-30 18:28:58
您的代码尝试按索引删除项,但每次删除索引为X的项时,索引为X+1的项将移至索引X。因此,每次删除索引为0的项时,索引为5的项将变为索引4。
您可以尝试对索引进行排序:
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);
}但删除项目的首选方式是按键值而不是索引值删除
https://stackoverflow.com/questions/10814370
复制相似问题