G
G
Glebster132022-04-02 04:46:03
C++ / C#
Glebster13, 2022-04-02 04:46:03

How to load data into DataGridView from text file?

Hello. There is a DataGridView1 , the columns are already created and named. You need to load data from a text file into this table.
I wrote the following code to populate the table programmatically:

private void DataInput_Click(object sender, EventArgs e){
   dataGridView1.Rows.Add("01.01.2022" "06:00" "Mersedes" "610-150" "6" "Иванов_Иван_Иванович" "Алексеев_Алексей_Алексеевич" 9999);
   dataGridView1.Rows.Add("01.01.2022" "06:00" "Mersedes" "610-150" "6" "Иванов_Иван_Иванович" "Алексеев_Алексей_Алексеевич" 9999);
    //И так далее
}

However, I need to load data from a file, and I don’t understand how to implement it. I've tried creating an array where the items are the required data and passing that as a parameter to dataGridView1.Rows.Add() . And it works, but if you set a value to an array from, for example, a TextBox element (separated by commas), then I will simply get a long string that will go to the zero element of the array.

I was told that for this (uploading data from a file) you need to make 2 classes: one is the DataTemplate template class , the second is a class for reading data from a text file LoadManager . I wrote them:
//Класс шаблон
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Kursovaya
{
    public class DataTemplate
    {
        public string DateWork { get; set; }
        public string Time { get; set; }
        public string BrandBus { get; set; }
        public string CityNumber { get; set; }
        public string RouteNumber { get; set; }
        public string DriverName { get; set; }
        public string CashierName { get; set; }
        public int Income { get; set; }
        public DataTemplate(string datework = "none",
                            string time = "none",
                            string brandbus = "none",
                            string citynumber = "none",
                            string routenumber = "none",
                            string drivername = "none",
                            string cashiername = "none",
                            int income = 0)
        {
            DateWork = datework;
            Time = time;
            BrandBus = brandbus;
            CityNumber = citynumber;
            RouteNumber = routenumber;
            DriverName = drivername;
            CashierName = cashiername;
            Income = income;
        }
    }
}

And the second class:
//Класс для считывания данных из текстового файла
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Kursovaya
{
    public class LoadManager
    {
        private bool PathCheck(string check)
        {
            if (!Directory.Exists(@"data"))
            {
                Directory.CreateDirectory(@"data");
                return false;
            }
            else
            {
                if (File.Exists(check))
                {
                    return File.ReadAllText(check).Length != 0;
                }
                return false;
            }
        }
        public Dictionary<string, DataTemplate> InputData()
        {
            Dictionary<string, DataTemplate> inputdata = new Dictionary<string, DataTemplate>();
            //Загрузка данных, если существуют
            if (PathCheck(@"data\inputdata.txt"))
            {
                // Чтение файла сохранения и создания из него массива
                string[] tmpRows = File.ReadAllText(@"data\inputdata.txt").Trim().Split('\n');
                string[] tmpColumns;
                foreach (string item in tmpRows)
                {
                    tmpColumns = item.Split('>');
 
                    // Создаём новые данные
                    DataTemplate datatemplate = new DataTemplate(tmpColumns[0],
                                                                tmpColumns[1],
                                                                tmpColumns[2],
                                                                tmpColumns[3],
                                                                tmpColumns[4],
                                                                tmpColumns[5],
                                                                tmpColumns[6],
                                                                int.Parse(tmpColumns[7])
                                                           );
                    // Добавляем данные в словарь
                    inputdata.Add(datatemplate.DateWork, datatemplate);
                }
            }
            return inputdata;
        }
    }
}


Another class called SaveManager was written. Its purpose is not clear to me, but it seems like it should help in solving the problem. Here is his code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Kursovaya
{
    public class SaveManager
    {
        private void PathCheck()
        {
            if (!Directory.Exists(@"data"))
            {
                Directory.CreateDirectory(@"data");
            }
        }
        public void InputData(Dictionary<string, DataTemplate> inputdata)
        {
            PathCheck();
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var item in inputdata)
            {
                stringBuilder.Append(string.Join(">", new string[]
                    {
                        item.Value.DateWork,
                        item.Value.Time,
                        item.Value.BrandBus,
                        item.Value.CityNumber,
                        item.Value.RouteNumber,
                        item.Value.DriverName,
                        item.Value.CashierName,
                        item.Value.Income.ToString()
 
                    }));
                stringBuilder.Append("\n");
            }
            // Запись в файл
            File.WriteAllText(@"data\inputdata.txt", stringBuilder.ToString());
        }
    }
}


A button with the corresponding code was also created:
private void button1_Click(object sender, EventArgs e)
        {
            SaveManager saveManager = new SaveManager();
            saveManager.InputData(datatemplate);
        }


And what to do next, I did not understand. Am I moving in the right direction at all? And what exactly do I need to do so that the data is entered into dataGridView1 from a text file?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Tsvetkov, 2022-04-02
@tsklab

.txt as a datasource for datagridview
How To Import Text File Data Into Datagridview In C#

K
Konstantin Teploukhov, 2022-04-02
@blood-moon

You can just read the file line by line and enter it with this code

dataGridView1.Rows.Add("01.01.2022" "06:00" "Mersedes" "610-150" "6" "Иванов_Иван_Иванович" "Алексеев_Алексей_Алексеевич" 9999);

ps: if you do not understand, then give an example of a couple of lines of the file, I will write the code for you myself

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question