1111
1111

Reputation: 39

c# Storing ListView Data into an Array and Sorting in Ascending Order

I have created a windows form application where I add info onto the list view, however I want to store the info for the next time the program is opened. How can I store the list view info onto an Array and also how can I sort it in Ascending order (the Due Date).

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();
    }
}

}

Thanks

Upvotes: 0

Views: 945

Answers (3)

XWIKO
XWIKO

Reputation: 343

WIth regard to ordering: you need an implementation of IComparer in order to sort the listview. for example:

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;
    }
}

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

You would implement it as follows:

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

With regard to getting an array. I would personally make an object out of the items and put it in a List. I dont know if it is the right way.

For example

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

you could make a list as follows

    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);

        }
    }

But you could always just make use the stringList and put that in a list.

//edit: sortorder should be Ascending like requested. Had Descending

Upvotes: 2

Leonard Klausmann
Leonard Klausmann

Reputation: 215

if you want to stick to information of a program you have save your information in a file or in a database.

As i can see, you want to save you're information locally: Therefore many opportunities are given.

I recommend you to implement a state class, where you save your information when you close the program and write them into a file. To save this class as File you have to make it serializable.(Walktrough)

For example:

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

how to open:

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

to fill the State class and save it in a file when the windows closes, intervene to the onclose event:

  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);               
    }

For the ordering you can call any time you want a Linq .OrderBy() or create your own order function.

Upvotes: 0

Nino
Nino

Reputation: 7115

There are few things to consider here: 1) use database. Data is more secure that way, easier to access, can hold large amounts of records etc. You can use serverless database engine such as SQLite 2) if you really want to avoid using database, use some class for storing data so you can later serialize it to XML and deserialize from XML. 3) you can store your data to local csv file if everything else fails. :)

Here is an example of serialization which writes data to application folder (in data.xml file) on form closing and loads it from file on form loading (very rudimentary one, but it can give you an idea...)

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; }
    }

Upvotes: 1

Related Questions