SIGN UP MEMBER LOGIN:    
ARTICLE

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

Posted by Ankur Gupta Articles | ASP.NET Controls in C# July 23, 2010
In this article we will see how to import data from text and CSV file to DataGridView in .Net.
Reader Level:
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.

Form2.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

erver'>
Login to add your contents and source code to this article
share this article :
post comment
 

Hi Ankur...With reference to ur link..i saw that link but thats not the thing i want. It printing thru printdocument. What i want is taking the total data from datagrid view it should print to a text file, in proper format and taking the proper looping...like we see any bill..like Srno Desc Qty Rate Price (this is just example) like this.. and header should repeat on change of 30 lines.. so this is what i want....so can u please guide me. I am using ADODB as u shown in ur post. Thanks in advance

Posted by kedar pawgi Mar 16, 2012

You Can find exactly what you want on following URL http://www.authorcode.com/how-to-print-datagridview-in-c/ Please read this and let me know if it solve your problem.

Posted by Ankur Gupta Mar 16, 2012

Hi ankur. your article is good for reading from file. But is it possible to let me know how can i send the datagrid data or an sql query data to a text file in formatted way like header and some line and their sum and then total sum...like printing a bill.i will be very thankful if u reply asap.

Posted by kedar pawgi Mar 10, 2012

How can you take the same example and make a textbox search with button to highlight a specific row based on the search. Please provide necessary code. By way, the original csv dataviewgrid works perfect so far!

Posted by Rob Garnett Feb 28, 2012

can you please help me to create a treeview in the datagrid what we made with csv file???

Posted by Karthiga M Mar 15, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Team Foundation Server Hosting
Become a Sponsor