0

I am working on a C# program that store the student name, student number, unit number, unit name, mark and attendance in an array. All the data are displayed in a ListView. How can I save the data from the array and then repopulate the array by using a Load Button? Thank you in advance.

public partial class Main : Form
{
    public Main()
    {
        InitializeComponent();

        //ListVIEW Properties
        listView.View = View.Details;
        listView.FullRowSelect = true;
    }

    private void insert(string StudentNumber, string StudentName, string UnitNumber, string UnitName, string Mark, string combobox)
    {
        // Array
        string[] row = { StudentNumber, StudentName, UnitNumber, UnitName, Mark, combobox };

        ListViewItem item = new ListViewItem(row);
        listView.Items.Add(item);
    }

    private void update()
    {
        //Update
        listView.SelectedItems[0].SubItems[0].Text = TXTStudentNumber.Text;
        listView.SelectedItems[0].SubItems[1].Text = TXTStudentName.Text;
        listView.SelectedItems[0].SubItems[2].Text = TXTUnitNumber.Text;
        listView.SelectedItems[0].SubItems[3].Text = TXTUnitName.Text;
        listView.SelectedItems[0].SubItems[4].Text = TXTMark.Text;
        listView.SelectedItems[0].SubItems[5].Text = comboBox1.Text;

        TXTStudentNumber.Text = "";
        TXTStudentName.Text = "";
        TXTUnitNumber.Text = "";
        TXTUnitName.Text = "";
        TXTMark.Text = "";
        comboBox1.Text = "";            
    }

    private void delete()
    {
        if (MessageBox.Show("Are you sure?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
        {
            listView.Items.RemoveAt(listView.SelectedIndices[0]);
        }            
        TXTStudentNumber.Text = "";
        TXTStudentName.Text = "";
        TXTUnitNumber.Text = "";
        TXTUnitName.Text = "";
        TXTMark.Text = "";
        comboBox1.Text = "";
    }

    private void btnInsert_Click(object sender, EventArgs e)
    {
        //Insert
        insert(TXTStudentNumber.Text, TXTStudentName.Text, TXTUnitNumber.Text, TXTUnitName.Text, TXTMark.Text, comboBox1.Text);

        // Clear All textBox after Pressing Button
        TXTStudentNumber.Text = "";
        TXTStudentName.Text = "";
        TXTUnitNumber.Text = "";
        TXTUnitName.Text = "";
        TXTMark.Text = "";
        comboBox1.Text = "";
    }

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

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

    //Clear Button
    private void btnClear_Click(object sender, EventArgs e)
    {
        TXTStudentNumber.Text = "";
        TXTStudentName.Text = "";
        TXTUnitNumber.Text = "";
        TXTUnitName.Text = "";
        TXTMark.Text = "";
        comboBox1.Text = "";
    }

    // ListView
    private void listView1_MouseClick(object sender, MouseEventArgs e)
    {
        TXTStudentNumber.Text = listView.SelectedItems[0].SubItems[0].Text;
        TXTStudentName.Text = listView.SelectedItems[0].SubItems[1].Text;
        TXTUnitNumber.Text = listView.SelectedItems[0].SubItems[2].Text;
        TXTUnitName.Text = listView.SelectedItems[0].SubItems[3].Text;
        TXTMark.Text = listView.SelectedItems[0].SubItems[4].Text;
        comboBox1.Text = listView.SelectedItems[0].SubItems[5].Text;
    } 
5
  • Are you using any database? Where do you want to save? Commented May 25, 2017 at 4:39
  • No I'm not using any database, I'm using only array. I just want a save button that can save the contents in my array or listView to my local storage and a load button to repopulate my array so that I can see my saved contents again in my listView. Commented May 25, 2017 at 13:13
  • So you want to save them to a file right? Commented May 25, 2017 at 13:24
  • Yes I want to save it to a file Commented May 25, 2017 at 15:00
  • Check my answer Commented May 25, 2017 at 15:35

2 Answers 2

1

array is not suitable in this case. Instead use list.

private List<Student> students = new List<Student>();
private void insert(string StudentNumber, string StudentName, string UnitNumber, string UnitName, string Mark, string combobox)
{
   Student s = new Student
   {
     StudentNumber =StudentNumber,
     StudentName =StudentName,
     UnitNumber =UnitNumber
     UnitName =UnitName,
     Mark = Mark
     Combobox = combobox
   };
  students.Add(s);
}


public class Student
{
  public string StudentNumber{get; set;}
  public string StudentName {get; set;}
  public string UnitNumber {get; set;}
  public string UnitName {get; set;}
  public string Mark {get; set;}
  public string Combobox {get;set;}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Would ICollection<Student> also be suitable?
ICollection is interface List is actual implementation to say. List inherit from ICollection and other interfaces. You could use ICollection as well. For more detail : stackoverflow.com/questions/7655845/…
0

Follow the below steps

  1. Add extension Method to convert your object to and from xml

ExtensionMethods class

public static class ExtensionMethods
{
    /// <summary>
    /// Converts given class to XML using xml serialization
    /// </summary>
    /// <typeparam name="T">Type of Class</typeparam>
    /// <param name="classObject">Class to be serialized</param>
    /// <returns>Xml string</returns>
    public static string ToXML<T>(this T classObject) where T : class
    {
        XmlSerializer xmls = new XmlSerializer(typeof(T));
        using (MemoryStream ms = new MemoryStream())
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = new UTF8Encoding(false);
            settings.Indent = true;
            settings.IndentChars = "\t";
            settings.NewLineChars = Environment.NewLine;
            settings.OmitXmlDeclaration = true;
            settings.ConformanceLevel = ConformanceLevel.Document;
            using (XmlWriter writer = XmlTextWriter.Create(ms, settings))
            {
                xmls.Serialize(writer, classObject);
            }

            string xml = Encoding.UTF8.GetString(ms.ToArray());
            return xml;
        }
    }

    /// <summary>
    /// Converts given XML string to class of type T
    /// </summary>
    /// <typeparam name="T">Type to be converted</typeparam>
    /// <param name="XmlData">xml string</param>
    /// <returns>class of Type T</returns>
    public static T ToClass<T>(this string XmlData)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        T newClass;
        using (XmlTextReader reader = new XmlTextReader(new StringReader(XmlData)))
        {
            //reader.Namespaces = false;
            newClass = (T)serializer.Deserialize(reader);
        }
        return newClass;
    }
}
  1. create a class to hold student information

student class

public class Student
{
  public string StudentNumber{get; set;}
  public string StudentName {get; set;}
  public string UnitNumber {get; set;}
  public string UnitName {get; set;}
  public string Mark {get; set;}
  public string Combobox {get;set;}
}
  1. In form load check if file exists

Form load

    //declare global variable for student list and filepath
    List<Student> students = new List<Student>();
    string FilePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName) + ".xml";
    private void Form1_Load(object sender, EventArgs e)
      {

            string XmlData = string.Empty;
            if (File.Exists(FilePath))
            {
                using (StreamReader sr = new StreamReader(FilePath))
                {
                    XmlData = sr.ReadToEnd(); 
                }
                students = XmlData.ToClass<List<Student>>();
            }      
      }
  1. In insert,update and delete operations save the xml file to file system

save xml

string XmlData = students.ToXML();
File.WriteAllText(FilePath, XmlData);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.