DataGridView records disappear after closing form

后端 未结 2 1775
我在风中等你
我在风中等你 2021-01-25 21:27

I have a datagridview that is not bound to a table in a database. The datagridview is being populated by the contents of a drop down list and a text box on a button click. I wan

相关标签:
2条回答
  • 2021-01-25 21:54

    You have many options. Here is a simple solution that uses XML serialization.

    Note that it makes a few assumptions:

    • The data all are strings
    • The DataGridView already has all the columns

    To save the other data types you should create a serializable structure!

    private void saveButton_Click(object sender, EventArgs e)
    {
        List<List<string>> data = new List<List<string>>();
    
        foreach(DataGridViewRow row  in dgInsertedInfo.Rows)
        {
           List<string> rowData = new List<string>();
           foreach (DataGridViewCell cell in row.Cells)
               rowData.Add(cell.FormattedValue.ToString());
           data.Add(rowData);
        }
    
        XmlSerializer xs = new XmlSerializer(data.GetType());
        using (TextWriter tw = new StreamWriter(yourFileName))
        {
            xs.Serialize(tw, data);
            tw.Close();
        }
    }
    
    private void loadButton_Click(object sender, EventArgs e)
    {
        List<List<string>> data = new List<List<string>>();
    
        XmlSerializer xs = new XmlSerializer(data.GetType());
        using (TextReader tr = new StreamReader(yourFileName))
             data = (List<List<string>>) xs.Deserialize(tr);
    
        foreach (List<string> rowData in data)
            dgInsertedInfo.Rows.Add(rowData.ToArray());
    }
    
    0 讨论(0)
  • 2021-01-25 22:12

    You can write your OWN class and save it as a setting-property.

    Class Settings:

    namespace MyNamespace
    {
        public class Settings
        {
            private ObservableCollection DataGridItemsProp;
            public ObservableCollection DataGridItems
            {
                 get { return DataGridItemsProp; }
                 set { DataGridItemsProp = value; }
            }
        }
    }
    

    Get and save your setting:

    //get settings
    var datagrid = Properties.Settings.Default.UserSettings;
    
    //save settings
    Properties.Settings.Default.UserSettings= datagrid;
    Properties.Settings.Default.Save();
    
    0 讨论(0)
提交回复
热议问题