Display a DataGrid by importing a CSV file in C#

Here is the steps to show a datagrid in a windows form from a CSV file.
Step 1. Put one button(name=brnbrowse) in your windows form
Step 2. Put one openFileDialog control(name=openFileDialog1)
Step 3. now add one event on the browse button as btnbrowse_Click
[code lang=”c#”]
private void btnbrowse_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
OleDbConnection odbconn;
OleDbDataAdapter da;
OleDbCommand cmd;
openFileDialog1.Filter = “CSV Files|*.csv”;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
string filename = file.Substring(file.LastIndexOf(“\\”) +1);
string Path = Directory.GetCurrentDirectory()+”\\ImportFiles”; //ImportFiles contains all imported files
if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); }

try
{
if(File.Exists(Path + “\\” + filename)){File.Delete(Path + “\\” + filename);}
File.Copy(file, Path + “\\” + filename);

string oledbconstring = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + Path+ “; Extended Properties=’text;HDR=Yes;FMT=Delimited'”;
odbconn = new OleDbConnection(oledbconstring);
odbconn.Open();
cmd = new OleDbCommand(“SELECT * FROM ” + fileName, odbconn);
da = new OleDbDataAdapter(cmd);
da.Fill(ds);
odbconn.Close();
dataGridView1.DataSource = ds.Tables[0].DefaultView;
}
catch (IOException)
{
}
}
} 0

About the author

Janaki(http://mjanaki.com) - A Software developer with 9+ years of experience in multiple technology projects across web, mobile, and cloud applications with expertise in PHP, C#, MySQL, Web services and open source platforms.

Similar Posts

Comments are closed.