Click here to Skip to main content
15,946,342 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
In my programme i want to import my csv file data into my datagridview into my load function,

I have no idea how to write the code for it.

here is my code:

C#
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;
using System.IO;
using VMwareRemoteConsoleTypeLib;

namespace OVF_ImportExport
{
    public partial class Form1 : Form
    {
        string sPath="";
        string sName = "";
        string delimiter = ",";
        string tablename = "export";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

           string filename= ("c:\\izaz\\test.csv");
            DataSet dataset = new DataSet();
            StreamReader sr = new StreamReader(filename);
            string allData = sr.ReadToEnd();
            string[] rows = allData.Split("\r".ToCharArray());
            foreach (string r in rows)
            {
                string[] items = r.Split(delimiter.ToCharArray());
                dataset.Tables[tablename].Rows.Add(items);
            }
            this.dataGridView1.DataSource = dataset.Tables[0].DefaultView;

                 
            
            //System.Data.OleDb.OleDbConnection MyConnection;
            //System.Data.DataSet DtSet;
            //System.Data.OleDb.OleDbDataAdapter MyCommand;
            //MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\psave\New folder\result.xlsx';Extended Properties=Excel 8.0;");
           // MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
           // MyCommand.TableMappings.Add("Name", "Path");
            //DtSet = new System.Data.DataSet();
            //MyCommand.Fill(DtSet);
            //dataGridView1.DataSource = DtSet.Tables[0];
            //MyConnection.Close();
            //dataGridView1.Columns[0].Width = 300;
            //dataGridView1.Columns[1].Width = 450;
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                sName = row.Cells[0].Value.ToString();
                sPath = row.Cells[1].Value.ToString();

                           
            }
        }

        private void BtnBrowse_Click(object sender, EventArgs e)
        {
            fbd.ShowDialog();
            TxtBrowsepath.Text = fbd.SelectedPath;
        }

        private void BtnCreate_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            StreamWriter file = new StreamWriter("Export.bat");
            file.WriteLine("c: ");
            file.WriteLine("cd \\");
            file.WriteLine("cd Program Files " );
            file.WriteLine("cd VMware" );
            file.WriteLine("cd VMware OVF Tool" );

            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                sName = row.Cells[0].Value.ToString();
                sPath = row.Cells[1].Value.ToString();

                //richTextBox1.Text = richTextBox1.Text + Environment.NewLine + sName;
                file.WriteLine("start ovftool.exe --powerOffSource vi://"+TxtUsername.Text + ":" + TxtPassword.Text + "@"+ TxtIP.Text + sPath + " " + "\"" + TxtBrowsepath.Text + "\\" + sName + "\\"+ sName + ".ovf" + "\"" + Environment.NewLine);
                   
                
            }
            file.WriteLine("pause");
            file.Close();
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        
        }
        
        }
Posted
Updated 30-Jun-15 2:49am
v3
Comments
Ralf Meier 30-Jun-15 5:15am    
I don't see, where the posted code is corresponding to your question.
In fact, you "only" have to read the lines of your CSV-File and ADD the Contents (perhaps as row) to the DGV ...
Shaik Izaz 30-Jun-15 5:21am    
i dint get you
Ralf Meier 30-Jun-15 6:09am    
Your Question was : import the data from a CSV-File to a DGV.
Your posted Code is how to write data from the DGV to a CSV-File.

So : how does your code match to your question ...?
Shaik Izaz 30-Jun-15 6:58am    
you are right! Actually, i was able to import xlsx file to DGV from load function and now i want to import csv file, so that why i just removed the xlsx import code from the load function and posted the full code....
Ralf Meier 30-Jun-15 8:03am    
But ... if you are able to import data from Excel-Files you must also be able to do that from CSV-Files. The File-reading-method is different - but the assignment to the DGV must be the same (for the same data).

1 solution

I have used solution like this, i hope this will work for you.
Import Data from Text and CSV file to DataGridView
STEP 1 : First i put the code in Button click event this will Browse your .csv in your computer, you can change to load function.
C#
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();
    }


STEP 2 : Create Import function(), this used in STEP 1
C#
if (txtFileName.Text.Trim() != string.Empty)
{
    try
    {
        DataTable dt = GetDataTable(txtFileName.Text);
        dataGridView1.DataSource = dt.DefaultView;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}


STEP 3 : Create something like return value from file data in a dataset.
C#
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;
}


note : If you have any error please try to set target platform to X86 of your application
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900