Scroll To Top
Reader Level:

Import Data from Text and CSV file to DataGridView in .Net

By Ankur Gupta on Jul 23, 2010
In this article we will see how to import data from text and CSV file to DataGridView in .Net.

First add a browser control, TextBox, Button and a DataGridView Control on form

Add the following code in Button Click Event


private void button1_Click_1(object sender, EventArgs e)


    OpenFileDialog fdlg = new OpenFileDialog();

    fdlg.Title = "Select file";

    fdlg.InitialDirectory = @"c:\";

    fdlg.FileName = txtFileName.Text;

    fdlg.Filter = "Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";

    fdlg.FilterIndex = 1;

    fdlg.RestoreDirectory = true;

    if (fdlg.ShowDialog() == DialogResult.OK)


        txtFileName.Text = fdlg.FileName;





When you select any Text or CSV file from Browser page then you get the full path of Text or CSV file.


You will pass this path in the following function that will return the dbf file data in a dataset.

public static DataTable GetDataTable(string strFileName)
Connection oConn = new ADODB.Connection();
"Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";", "", "", 0);
string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
Recordset rs = new ADODB.Recordset();
OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
DataTable dt = new DataTable();
"Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";",
CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
    adapter.Fill(dt, rs);
return dt;

You can easily show dataset data in Datagridview.

private void Import()
if (txtFileName.Text.Trim() != string.Empty)
DataTable dt = GetDataTable(txtFileName.Text);
            dataGridView1.DataSource = dt.DefaultView;
catch (Exception ex)