This tutorial demonstrates how a csv file can be used to bind data to DataGridView of C#.
The code uses System.IO.File.ReadAllText to read the file’s contents into a string. It then uses Split to break the file into lines, ignoring any blank lines.
The code then loops through the lines using Split to split the lines into fields and adding their values to the array. When it’s done, the method returns the two-dimensional array of strings.
Form Design:
In our first approach, we are going to create textBox, dataGridView, openFileDialog and Button Controls at design-time using the Forms designer.
Source Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | 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; } } } } |
Output:
Thanks!
I’m getting:
The name ‘txtFile’ does not exist in the current context
just type in your textbox name instead, also in button action properties choose click action to your button.
and for BindData what is the Default name in .net
Nice and simple! Thanks!
thank you very much! is perfect!
how do you do this in 2 tier form where presentation is in windows form openfiledialog and data layer is in class library and all code is in data tier after clicking the button?
Hi, i got this error after i have import The CSV file. Does anyone have any idea?
‘IndexOutOfRangeException‘