Reader Level:
ARTICLE

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

Posted by Ankur Gupta Articles | ASP.NET Controls July 23, 2010
In this article we will see how to import data from text and CSV file to DataGridView in .Net.
  • 1
  • 0
  • 87056
Download Files:
 

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

Add the following code in Button Click Event

Form1.JPG

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;

        Import();

        Application.DoEvents();

    }

}


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

a1.jpg

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)
{
    ADODB.
Connection oConn = new ADODB.Connection();
    oConn.Open(
"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) + "]";
    ADODB.
Recordset rs = new ADODB.Recordset();
    System.Data.OleDb.
OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
    
DataTable dt = new DataTable();
    rs.Open(strQuery,
"Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";",
        ADODB.
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)
    {
        
try
        {
            
DataTable dt = GetDataTable(txtFileName.Text);
            dataGridView1.DataSource = dt.DefaultView;
        }
        
catch (Exception ex)
        {
            
MessageBox.Show(ex.Message.ToString());
        }
    }
}

Output:

 Form3.JPG

Article Extensions
Contents added by Mariammal G on Oct 10, 2012
COMMENT USING

Trending up