首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从ListBox中删除多个项目;在XML中更新

从ListBox中删除多个项目;在XML中更新
EN

Stack Overflow用户
提问于 2012-05-30 18:21:02
回答 1查看 980关注 0票数 1

我使用XML文件来存储ListBox中的内容并在其上显示内容。

下面是一个示例XML文件;

代码语言:javascript
运行
复制
<?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时,结果更加奇怪。

我做错了什么吗?

如何获取多个项目的索引并正确处理?

下面是我的代码:

代码语言:javascript
运行
复制
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);
            }
        }
    }
}
EN

Stack Overflow用户

回答已采纳

发布于 2012-05-30 18:28:58

您的代码尝试按索引删除项,但每次删除索引为X的项时,索引为X+1的项将移至索引X。因此,每次删除索引为0的项时,索引为5的项将变为索引4。

您可以尝试对索引进行排序:

代码语言:javascript
运行
复制
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);
}

但删除项目的首选方式是按键值而不是索引值删除

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10814370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档