C# 保存并重新填充数组中的数据

Posted

技术标签:

【中文标题】C# 保存并重新填充数组中的数据【英文标题】:C# Save and repopulate data from array 【发布时间】:2017-05-25 03:51:02 【问题描述】:

我正在开发一个 C# 程序,该程序将学生姓名、学生编号、单元编号、单元名称、分数和出勤率存储在一个数组中。所有数据都显示在 ListView 中。如何保存数组中的数据,然后使用加载按钮重新填充数组?提前谢谢你。

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;
     

【问题讨论】:

你在使用任何数据库吗?你想保存在哪里? 不,我没有使用任何数据库,我只使用数组。我只想要一个保存按钮,可以将我的数组或 listView 中的内容保存到我的本地存储,以及一个加载按钮来重新填充我的数组,以便我可以在我的 listView 中再次看到我保存的内容。 所以你想把它们保存到一个文件中对吧? 是的,我想将其保存到文件中 检查我的答案 【参考方案1】:

array 在这种情况下不适合。而是使用列表。

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

【讨论】:

ICollection&lt;Student&gt; 也适合吗? ICollection 是接口 List 是实际实现要说的。 List 继承自 ICollection 和其他接口。您也可以使用 ICollection。更多详情:***.com/questions/7655845/…【参考方案2】:

按照以下步骤进行

    添加扩展方法以将您的对象与 xml 相互转换

ExtensionMethods 类

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;
    

    创建一个类来保存学生信息

学生班

public class Student

  public string StudentNumberget; 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;

    在表单加载中检查文件是否存在

表单加载

    //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>>();
                  
      
    在插入、更新和删除操作中,将 xml 文件保存到文件系统中

保存 xml

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

【讨论】:

以上是关于C# 保存并重新填充数组中的数据的主要内容,如果未能解决你的问题,请参考以下文章

在 C# 中为本地记分板保存数组

打开图像并使用相同的参数重新保存它,c#

在 vue 中保存预填充的输入

从本地存储动态重新填充表行

如何保存数组?

更改数组后无法在 Tableview 中重新加载数据?