c#将ListView数据存储到数组中并按升序排序

时间:2016-04-20 12:36:59

标签: c# arrays winforms sorting

我创建了一个Windows窗体应用程序,我将信息添加到列表视图中,但是我想在下次打开程序时存储信息。如何将列表视图信息存储到数组中,以及如何按升序(截止日期)对其进行排序。

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

namespace WindowsFormsApplication6
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

    private void Form1_Load(object sender, EventArgs e)
    {
        listView1.View = View.Details;
        listView1.FullRowSelect = true;

        listView1.Columns.Add("Due Date", 150);
        listView1.Columns.Add("Module", 150);
        listView1.Columns.Add("Title", 150);
    }

    private void add(string DueDate, String Module, String Title)
    {
        string[] row = { DueDate, Module, Title };
        ListViewItem item = new ListViewItem(row);

        listView1.Items.Add(item);
    }

    private void listView1_MouseClick(object sender, MouseEventArgs e)
    {
        String Duedate = listView1.SelectedItems[0].SubItems[0].Text;
        String Module = listView1.SelectedItems[0].SubItems[1].Text;
        String Title = listView1.SelectedItems[0].SubItems[2].Text;

        textBox1.Text = Duedate;
        textBox2.Text = Module;
        textBox3.Text = Title;
    }

    private void btnAdd_Click(object sender, EventArgs e)
    {
        add(textBox1.Text, textBox2.Text, textBox3.Text);

        textBox1.Text = "";
        textBox2.Text = "";
        textBox3.Text = "";
    }

    private void btnClear_Click(object sender, EventArgs e)
    {
        listView1.Items.Clear();

        textBox1.Text = "";
        textBox2.Text = "";
        textBox3.Text = "";
    }

    private void update()
    {
        listView1.SelectedItems[0].SubItems[0].Text = textBox1.Text;
        listView1.SelectedItems[0].SubItems[1].Text = textBox2.Text;
        listView1.SelectedItems[0].SubItems[2].Text = textBox3.Text;

        textBox1.Text = "";
        textBox2.Text = "";
        textBox3.Text = "";
    }

    private void btnUpdate_Click(object sender, EventArgs e)
    {
        update();
    }

    private void delete()
    {
        if(MessageBox.Show("Are you sure you want to Delete", "Delete", MessageBoxButtons.OKCancel,MessageBoxIcon.Warning)== DialogResult.OK)
        {
            listView1.Items.RemoveAt(listView1.SelectedIndices[0]);

            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
        }
    }

    private void btnDelete_Click(object sender, EventArgs e)
    {
        delete();
    }
}

}

由于

3 个答案:

答案 0 :(得分:2)

关于排序:您需要IComparer的实现才能对listview进行排序。例如:

class ListViewItemComparer : IComparer
{
    private int col;
    public ListViewItemComparer()
    {
        col = 0;
    }
    public ListViewItemComparer(int column)
    {
        col = column;
    }
    public int Compare(object x, object y)
    {
        int returnVal = -1;
        returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text,
        ((ListViewItem)y).SubItems[col].Text);
        return returnVal;
    }
}

来源:https://msdn.microsoft.com/en-us/library/ms996467.aspx

您可以按如下方式实施:

    private void btnSort_Click(object sender, EventArgs e)
    {
        listView1.ListViewItemSorter = new ListViewItemComparer(2); // Column number 3
        listView1.Sorting = SortOrder.Ascending;
        listView1.Sort();            
    }

关于获取数组。我会亲自从物品中制作一个物品并将其放入清单中。我不知道这是不是正确的方式。

例如

public class ExampleObject
{
    public string DueDate { get; set; }
    public string Module { get; set; }
    public string Title { get; set; }
}

您可以按如下方式列出

    private void btnList_Click(object sender, EventArgs e)
    {
        List<ExampleObject> templist = new List<ExampleObject>();

        var collection = listView1.Items;
        foreach (var item in collection)
        {
            ListViewItem obj = (ListViewItem)item;
            var subitems = obj.SubItems;
            List<string> stringlist = new List<string>();

            foreach (ListViewSubItem subitem in subitems)
            {
                stringlist.Add(subitem.Text);
            }

            ExampleObject tempobject = new ExampleObject()
            {
                DueDate = stringlist[0],
                Module = stringlist[1],
                Title = stringlist[2]

            };
            templist.Add(tempobject);

        }
    }

但你总是可以使用stringList并将其放在列表中。

// edit:sortorder应该像要求一样升序。已经下降了

答案 1 :(得分:1)

这里有几件事要考虑: 1)使用数据库。数据更安全,更容易访问,可以容纳大量记录等。您可以使用无服务器数据库引擎,如SQLite 2)如果你真的想避免使用数据库,可以使用一些类来存储数据,这样你以后可以将它序列化为XML并从XML反序列化。 3)如果其他一切都失败,您可以将数据存储到本地csv文件。 :)

这是一个序列化示例,它在表单关闭时将数据写入应用程序文件夹(在data.xml文件中),并在表单加载时从文件加载 (非常简陋的,但它可以给你一个想法...)

using System.Xml.Serialization;

(...)

 public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                listView1.View = View.Details;
                listView1.FullRowSelect = true;

            LoadDataFromDisk();

                listView1.Columns.Add("Due Date", 150);
                listView1.Columns.Add("Module", 150);
                listView1.Columns.Add("Title", 150);
            }

            private void add(string DueDate, String Module, String Title)
            {
                string[] row = { DueDate, Module, Title };
                ListViewItem item = new ListViewItem(row);

                listView1.Items.Add(item);
            }

            private void listView1_MouseClick(object sender, MouseEventArgs e)
            {
                String Duedate = listView1.SelectedItems[0].SubItems[0].Text;
                String Module = listView1.SelectedItems[0].SubItems[1].Text;
                String Title = listView1.SelectedItems[0].SubItems[2].Text;

                textBox1.Text = Duedate;
                textBox2.Text = Module;
                textBox3.Text = Title;
            }

            private void btnAdd_Click(object sender, EventArgs e)
            {
                add(textBox1.Text, textBox2.Text, textBox3.Text);

                textBox1.Text = "";
                textBox2.Text = "";
                textBox3.Text = "";
            }

            private void btnClear_Click(object sender, EventArgs e)
            {
                listView1.Items.Clear();

                textBox1.Text = "";
                textBox2.Text = "";
                textBox3.Text = "";
            }

            private void update()
            {
                listView1.SelectedItems[0].SubItems[0].Text = textBox1.Text;
                listView1.SelectedItems[0].SubItems[1].Text = textBox2.Text;
                listView1.SelectedItems[0].SubItems[2].Text = textBox3.Text;

                textBox1.Text = "";
                textBox2.Text = "";
                textBox3.Text = "";
            }

            private void btnUpdate_Click(object sender, EventArgs e)
            {
                update();
            }

            private void delete()
            {
                if (MessageBox.Show("Are you sure you want to Delete", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    listView1.Items.RemoveAt(listView1.SelectedIndices[0]);

                    textBox1.Text = "";
                    textBox2.Text = "";
                    textBox3.Text = "";
                }
            }

            private void btnDelete_Click(object sender, EventArgs e)
            {
                delete();
            }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            SaveDataToDisk();
        }

        private void SaveDataToDisk()
        {
            List<MyData> myDataList = new List<MyData>();

            foreach (ListViewItem lvi in this.listView1.Items)
            {
                MyData d = new MyData();

                d.DueDate = lvi.SubItems[0].Text;
                d.Module = lvi.SubItems[1].Text;
                d.Title = lvi.SubItems[2].Text;

                myDataList.Add(d);
            }

            XmlSerializer serializer = new XmlSerializer(myDataList.GetType());
            string dataFile = Path.Combine(Application.StartupPath, "data.xml");
            TextWriter fileStream = new StreamWriter(dataFile);
            serializer.Serialize(fileStream, myDataList);
            fileStream.Close();
        }

        private void LoadDataFromDisk()
        {
            string dataFile = Path.Combine(Application.StartupPath, "data.xml");
            FileStream fileStream = new FileStream(dataFile, FileMode.Open, FileAccess.Read, FileShare.Read);

            List<MyData> data = new List<MyData>();
            XmlSerializer serializer = new XmlSerializer(data.GetType());

            data = (List<MyData>)serializer.Deserialize(fileStream);

            fileStream.Close();

            listView1.Items.Clear();
            foreach (var d in data)
            {
                add(d.DueDate, d.Module, d.Title);
            }
        }
    }

    public class MyData
    {
        public string  DueDate { get; set; }
        public string Title { get; set; }
        public string Module { get; set; }
    }

答案 2 :(得分:0)

如果您想坚持程序的信息,您已将信息保存在文件或数据库中。

我可以看到,你想在本地保存你的信息:因此给了很多机会。

我建议您实现一个状态类,在关闭程序并将其写入文件时保存信息。要将此类保存为File,您必须使其可序列化。(Walktrough

例如:

[Serializable()]
public class State
    {
        public List<ListViewDataItem> ListViewChoises;
    }

如何打开:

 if (File.Exists(FileName))
{
    Stream TestFileStream = File.OpenRead(FileName);
    BinaryFormatter deserializer = new BinaryFormatter();
    var loaded_state = (State)deserializer.Deserialize(TestFileStream);
    TestFileStream.Close();
}

填写State类并在窗口关闭时将其保存在文件中,介入onclose事件:

  protected override void OnFormClosing(FormClosingEventArgs e)
    {
    State state = new State(){Listbox1Choise = (ListboxChoises)System.Enum.Parse(typeof(ListboxChoises),  listView1.SelectedItems[0].SubItems[0].Text);

    Stream TestFileStream = File.Create(FileName);
    BinaryFormatter serializer = new BinaryFormatter();
    serializer.Serialize(TestFileStream, state);
    TestFileStream.Close();    

    base.OnFormClosing(e);               
    }

对于订购,您可以随时调用Linq .OrderBy()或创建自己的订单功能。