1

I've successfully loaded a .csv file into an array which i set into a dataset/datagridview control for viewing. The issue I have been having is trying to think of a way to:

  • Select columns of imported data (in terms of UI)
  • Store the fresh selection of information for review

The current code i have allows the user to browse for the file on their system and stores the data in an array and sets it into a datatable.

    private void btnBrowse_Click(object sender, EventArgs e)
    {
        #region Local Variables
        int nRows = 0;      //Row Counter
        int icol = 0;       //Index value for Columns -> fArray
        int irow = 0;       //Index value for Row -> fArray
        string Line;        //Temp string value for storing lines
        #endregion

        #region File Open Parameters
        //file open parameters
        OpenFileDialog fopen = new OpenFileDialog();
        fopen.Title = "Choose file...";
        fopen.Filter = "Comma Seperated Values|*.csv";
        fopen.InitialDirectory = @"C:\";
        #endregion

        if (fopen.ShowDialog() == DialogResult.OK) //Show file open dialog and check if ok has been pressed
        {
            #region progress bar initialisation
            //initialize progress bar
            pb.Location = new Point(60, 209);
            pb.Width = 516;
            pb.Height = 23;
            pb.Style = ProgressBarStyle.Continuous;
            pnlStep1.Controls.Add(pb);
            #endregion

            try
            {
                StreamReader fReader = new StreamReader(fopen.FileName);

                #region Array Index Counters
                //Count Columns for fArray index
                string count = fReader.ReadLine();
                string[] tmpCount = count.Split(',');
                fReader.Close();

                //Count Rows for fArray index
                fReader = new StreamReader(fopen.FileName); //begin reading from line 1
                while ((fReader.ReadLine()) != null)
                {
                    nRows++;
                }

                fArray = new string[nRows, tmpCount.Length];
                fReader.Close();
                //End count
                #endregion

                #region Load File Contents
                fReader = new StreamReader(fopen.FileName); //begin reading from line 1
                DataSet ds = new DataSet();
                dt = ds.Tables.Add("ImportData");

                while ((Line = fReader.ReadLine()) != null)
                {
                    string[] row = Line.Split(',');
                    foreach (string column in row)
                    {
                        fArray[irow, icol] = column;
                        icol++;
                    }
                    icol = 0;
                    recordCountLabel.Text = irow.ToString(); //NEEDS LOOKING AT
                    pb.Value = (irow * 100) / fArray.GetLength(0);
                    irow++;
                }
                pb.Value = 100;
                fReader.Close();
                #endregion

                #region Add data to dgImport
                for (int i = 0; i < fArray.GetLength(1); i++) //Add Columns to empty DataGridView
                {
                    dt.Columns.Add("Field " + i.ToString());
                }

                for (int i = 0; i < 3; i++) //Insert data into DataGridView (use fArray.GetLength(0) for entire database or use 5 for sample data)
                {
                    DataRow row = dt.NewRow();
                    for (int j = 0; j < fArray.GetLength(1); j++)
                    {
                        row[j] = fArray[i, j].Trim();
                    }
                    dt.Rows.Add(row);
                    dgImport.DataSource = dt;
                }

                btnNext2.Enabled = true;
                #endregion

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Could not read file from disk.\r\nOriginal error: " + ex.Message);
            }
        }   
    }

Any help would be greatly appreciated :).

EDIT: Sorry to be a pain again i forgot to mention, i show a few sample rows of data in a datagridview control and was looking at providing a list of dynamically created checkboxes allowing the user to tick what columns he/she wants to select (essentially copying only the data that is selected).

1
  • 1
    Or use linq; much faster than oledb Commented Jul 9, 2012 at 21:49

1 Answer 1

2

You need to read csv using OleDb Provider. That way you may specify the set of columns you want to include in SELECT statement.

EDIT:

 string location=@"c:\folder\";
 string cnstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + location + ";Extended Properties=\"text;HDR=No;FMT=Delimited\";";
 string sql = "select F2,F1 from test.csv";

 using (OleDbDataAdapter adp = new OleDbDataAdapter(sql, cnstr))
  {
    DataTable dt = new DataTable();
    adp.Fill(dt);

    foreach (DataRow row in dt.Rows)
    {
       Console.WriteLine(row[0] + " " + row[1]);
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

A part of the requirements is that a customer might not always have column headers defined which made me go against that idea a bit.
You may specify the column alias F1 (for first column),F2 to select the columns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.