简体   繁体   中英

How to import data into datagridview from .txt file

I have create a method that stores data from a datagridview into a.txt file. This runs when the application closes and works as I would like it too. I was wondering how I can then load this data back into the datagrid when the application loads again. This is the method that stores the data:

private void StoreData()
{
    var dataGrid = dataGridViewRegisteredVehicles;
    TextWriter writer = new StreamWriter(@"C:\DatagridStorage\Text.txt");
    for (int i = 0; i < dataGrid.Rows.Count; i++)
    {
        for (int j = 0; j < dataGrid.Columns.Count; j++)
        {
            writer.Write("\t" + dataGrid.Rows[i].Cells[j].Value.ToString() + "\t" + "|");
        }
        writer.WriteLine("");
        writer.WriteLine("-----------------------------------------------------");
    }
    writer.Close();
    MessageBox.Show("Data Exported");
}

Try this for ideas:

  • Make a new form

  • Put a datagridview on your form

  • Put this code in the FormClosing event (double click FormClosing in the formdesigner, in the lightning bolt of the properties grid after clicking the background of the form)

    (dataGridView1.DataSource as DataTable).WriteXml("grid.xml");
  • Put this code in the FormLoad event
    var dt = new DataTable();
    if(File.Exists("grid.xml")){
      dt.ReadXml("grid.xml");
    } else {
      dt.Columns.Add("Name");
      dt.Columns.Add("Age");
    }
    dataGridView1.DataSource = dt;
 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM