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;
    } 
Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
Hans
  • 11
  • 2

2 Answers2

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;}
}
Bhuban Shrestha
  • 1,304
  • 11
  • 27
  • Would `ICollection` also be suitable? – Chef_Code May 25 '17 at 04:51
  • 1
    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 : https://stackoverflow.com/questions/7655845/icollectiont-vs-listt-in-entity-framework – Bhuban Shrestha May 25 '17 at 04:54
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);
Krishna
  • 1,945
  • 1
  • 13
  • 24