Fayy
Fayy

Reputation: 9

how to read CSV and put it into DataGrid view one by one C#

i want to read CSV on the excel and then, put in the db grid one by one.

For example in 1 hour there are 200 data, for example, in the 10th minute, 2 data can be displayed. then 15 data in the 25th minute and 72 data in the 45th minute.

and how to make it? please help me

Upvotes: 0

Views: 217

Answers (1)

Metallic Skeleton
Metallic Skeleton

Reputation: 699

You need a background process ( different thread) to read the data periodically. To check the data periodically, you can use Timer in C#.

Here is the CSV Reader:

 public class CSVReader
  {
    string appLocation = System.IO.Directory.GetCurrentDirectory();


    public List<MyDataModel> GetNewCSVValue()
    {
        StreamReader streamReader;
        List<MyDataModel> myDataModels = new List<MyDataModel>();
        MyDataModel myDataModel = null;

        var mydataFile = "../../../UnProcessed/data.csv";

        if (File.Exists(mydataFile))
        {
            try
            {
                streamReader = File.OpenText(mydataFile);

                while (!streamReader.EndOfStream)
                {
                    var valueLine = streamReader.ReadLine();

                    myDataModel = new MyDataModel();

                    var csvValues = valueLine.Split(',');
                    if (csvValues != null)
                    {
                        myDataModel.Column1 = csvValues[0];
                        myDataModel.Column2 = csvValues[1];
                        myDataModels.Add(myDataModel);
                    }

                }

                streamReader.Close();
                streamReader = null;

                // Move the data file to Processed folder
                //File.Move(mydataFile, 
          // "../../../Processed/data"+DateTime.Now.ToString()+".csv");
            }
            catch (Exception ex)
            {
                streamReader = null;
            }
        }

        return myDataModels;
    }

}

Please add a Data Grid view in you main form and name it as dataGridView1. Here is the code of main form.

using System;
using System.Collections.Generic;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Threading;

namespace DataGrid
{
public partial class Form1 : Form
{

    List<MyDataModel> myDataModels = new List<MyDataModel>();

    public Form1()
    {
        InitializeComponent();
        // Read csv data at the begining
        ReadCSVData();
        // Set data in the grid
        dataGridView1.DataSource = myDataModels;

        // Then read the data file in regular interval and set in the grid
        StartAutoRefresh();
    }

    private void ReadCSVData()
    {
        CSVReader cSVReader = new CSVReader();
        var newCSVDataRows = cSVReader.GetNewCSVValue();
        if (newCSVDataRows != null)
        {
            myDataModels.AddRange(newCSVDataRows);
        }            
    }

    #region Timer 
    private static System.Timers.Timer _timer;

    private void StartAutoRefresh()
    {
        Console.WriteLine("Start the Datafetch " + DateTime.Now);

        if (_timer == null)
        {
            int dataFetchInterval = 1;

            dataFetchInterval = dataFetchInterval * 60 * 1000;

            _timer = new System.Timers.Timer(dataFetchInterval);
            _timer.Elapsed += new 
    ElapsedEventHandler(FetchTripsOfTheWeek);

            _timer.Interval = dataFetchInterval;
            _timer.Enabled = true;
        }
        else
        {
            _timer.Enabled = true;
        }

    }

    public void StopAutoRefresh()
    {
        if (_timer != null)
        {
            _timer.Enabled = false;
            _timer.Dispose();
            _timer = null;
        }
    }


    public void FetchTripsOfTheWeek(object source, ElapsedEventArgs e)
    {
        bool isResourcesLoaded = false;
        executeActionOnBackgroundThread(
           "Loading data ...",
           () =>
           {
               try
               {
                   ReadCSVData();
                   isResourcesLoaded = true;
               }
               catch (Exception exception)
               {
                   var message = exception.Message;

                   MessageBox.Show(message);

                   isResourcesLoaded = false;
               }
           },

           () =>
           {
               var result = true;
               if (isResourcesLoaded)
               {
                   // Set data in the grid
                   dataGridView1.DataSource = null;
                   dataGridView1.DataSource = myDataModels;
                   dataGridView1.Refresh();
               }
               return result;
           },

           () =>
           {
               // Do extra things, like, setting readonly mode etc
           });
    }

    private void executeActionOnBackgroundThread(string indicatorMessage, 
    System.Action backgroundAction, System.Func<bool> uiAction, 
   System.ActiononCompletedAction = null)
    {
        System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            backgroundAction?.Invoke();

            BeginInvoke(new System.Action(() =>
            {
                var success = uiAction?.Invoke();

                onCompletedAction?.Invoke();

            }), null);
        });
    }

    #endregion
}

}

You down load the full project from here https://drive.google.com/open?id=1ChLY7IydYM5OT5sOTUXjjV-6vfrgUeoD

Hope you can solve the issue. Good luck.

Upvotes: 1

Related Questions