Из этой статьи вы узнаете, как использовать csv-файл для привязки данных к DataGridView языка C#.
Код использует System.IO.File.ReadAllText для чтения содержимого файла в строку. Затем он использует Split, чтобы разбить файл на строки, игнорируя любые пустые строки.
Затем код циклически проходит по строкам, используя Split для разделения строк на поля и добавления их значений в массив. Когда это сделано, метод возвращает двумерный массив строк.
В нашем первом подходе мы собираемся создать элементы управления textBox , dataGridView, openFileDialog и Button во время разработки с помощью конструктора форм.
исходный код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace csvtodatagrid
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
txtFile.Text = openFileDialog1.FileName;
BindData(txtFile.Text);
}
private void BindData(string filePath)
{
DataTable dt = new DataTable();
string[] lines = System.IO.File.ReadAllLines(filePath);
if(lines.Length>0)
{
//first line to create header
string firstLine = lines[0];
string[] headerLabels = firstLine.Split(',');
foreach(string headerWord in headerLabels)
{
dt.Columns.Add(new DataColumn(headerWord));
}
//For Data
for(int i=1;i<lines.Length;i++)
{
string[] dataWords = lines[i].Split(',');
DataRow dr = dt.NewRow();
int columnIndex = 0;
foreach(string headerWord in headerLabels)
{
dr[headerWord] = dataWords[columnIndex++];
}
dt.Rows.Add(dr);
}
}
if(dt.Rows.Count>0)
{
dataGridView1.DataSource = dt;
}
}
}
}
1
