Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I got an issue i cannot help myself out with.

My program loads an CSV (excel) file which has a database build-in all assigned in [a] line1.

ex; A-1 = testcol,testcol,testcol
ex; A-2 = value1,value2,value3

now i've got my things to read just fine in their own columns, but i cant seem to save them correctly.

once its saved my program decides to add another Column and a whole Empty Row.

so my file now occurs as;

ex; A-1 = testcol,testcol,testcol,column1
ex; A-2 = NULL,NULL,NULL,NULL

i would like to remove the Column1 (and save the file without doing this).
aswell as removing the empty row..

This is how my save procedure looks like:
C#
/* Used to count the line(s)*/
toolStripProgressBar1.Value = 0;

// Don't save if no data is returned
if (dataGridView1.Rows.Count == 0)
{
   return;
}

StringBuilder sb = new StringBuilder();

// Column headers
string columnsHeader = "";
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
   columnsHeader += dataGridView1.Columns[i].Name + ",";
}
sb.Append(columnsHeader + Environment.NewLine);

// Go through each cell in the datagridview
foreach (DataGridViewRow dgvRow in dataGridView1.Rows)
{
   // Make sure it's not an empty row.
   if (!dgvRow.IsNewRow)
   {
      for (int c = 0; c < dgvRow.Cells.Count; c++)
      {
         // Append the cells data followed by a comma to delimit.
         sb.Append(dgvRow.Cells[c].Value + ",");
      }
      // Add a new line in the text file.
      sb.Append(Environment.NewLine);
   }
}

// Load up the save file dialog with the default option as saving as a .csv file.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV files (*.csv)|*.csv";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
   int maxnumber = 100;
   toolStripProgressBar1.Value = 0;
   toolStripProgressBar1.Maximum = maxnumber;
   for (int x = 0; x <= maxnumber - 1; x++)
   {
      toolStripProgressBar1.Value += 1;

      // If they've selected a save location...
      using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
      {
         string result;
         result = Path.GetFileNameWithoutExtension(sfd.FileName);

         tabPage1.Text = result;
         toolStripStatusLabel1.Text = "[1]File Saved! - " + result;

         // Write the stringbuilder text to the the file.
         sw.WriteLine(sb.ToString());
      }
   }
}


i have no space here on this website to either put my load example here, but its below this line incase you do want to read it all.

C#
OpenFileDialog openFile = new OpenFileDialog();
openFile.InitialDirectory = "c:\\";                                   //" // [Edit] Colour fix
openFile.Filter = " All Files (*.*) | *.*| CSV Files (*.csv) | *.csv";
openFile.FilterIndex = 2;
openFile.RestoreDirectory = true;

try
{
   /* Always Clear the datagrid first before loading again.*/
   if (this.dataGridView1.DataSource != null)
   {
      this.dataGridView1.DataSource = null;
   }
   else
   {
      this.dataGridView1.Rows.Clear();
   }

   /* Used to count the line(s)*/
   toolStripProgressBar1.Value = 0;

   if (openFile.ShowDialog() == DialogResult.OK)
   {

      /* Make sure combobox is cleared out before we load another one.*/
      comboBox1.Items.Clear();

      /* Define file name = file selected*/
      string file = openFile.FileName;
      StreamReader sr = new StreamReader(file);

      /*Result = filename*/
      string result;
      result = Path.GetFileNameWithoutExtension(file);

      tabPage1.Text = result;

      /* gets all the lines of the csv */
      string[] str = File.ReadAllLines(file);

      /* creates a data table*/
      DataTable dt = new DataTable();

      /* gets the column headers from the first line*/
      string[] temp = str[0].Split(',');

      /* creates columns of the gridview base on what is stored in the temp array */
      foreach (string t in temp)
      {
         dt.Columns.Add(t, typeof(string));
         comboBox1.Items.Add(t);
      }

      /* gets the amount of row(s) loaded. */
      var lines = File.ReadAllLines(file);
      var count = lines.Length;

      /* retrieves the rows after the first row and adds it to the datatable */
      for (int i = 1; i &lt; str.Length; i++)
      {
         toolStripProgressBar1.Value += 1;
         toolStripProgressBar1.Maximum = count;

         List<string> list = new List<string>(str[i].Split(','));

         if (str[i].Contains('"'))
         {
            for (int j = 0; j < list.Count; j++)
            {
               while ((list[j].Split('"').Length % 2) == 1)
               {
                  list[j] += "," + list[j + 1];
                  list.RemoveAt(j + 1);
               }

               if (list[j].StartsWith("\"") && list[j].EndsWith("\""))
                  list[j] = list[j].Substring(1, list[j].Length - 2);
            }
         }
         else
         {
            string[] t = str[i].Split(',');
            dt.Rows.Add(t);
         }
      }

      //The datagridview will now be populated with data from all the other rows except the first.
      dataGridView1.DataSource = dt;
      toolStripStatusLabel1.Text = "[1]Lines loaded: " + count;
   }
}
catch (Exception ex)
{
   ////If there is a issue, report it to the user, but also to the event logger.
   MessageBox.Show("[1]Error: The CSV you selected could not be loaded \n\n" + ex.Message, "Load Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}


please help me, i have no idea how to fix this and its quite important i get my database saving right :)
Posted
Updated 13-May-14 12:18pm
v3
Comments
ZurdoDev 13-May-14 21:06pm    
All you have to do is debug it and watch what happens.

But shouldn't i < dataGridView1.Columns.Count actually be i < dataGridView1.Columns.Count -1 ?
misterd1 14-May-14 9:56am    
stupid question; how exactly do i debug it?<br>
<br>
i switched from my old & trusted Visual Studio 2010 to 2013, i just cant seem to find it / how to.

tried ''i < dataGridView1.Columns.Count -1'' file saves, but i can't open it anymore

error that occurs is ; 'the inputmatrix is longer than the columns in this tabel'

if i restore it to ''i < dataGridView1.Columns.Count'' the file succesfully saves it and opens it but i get the 'bug' again.
gggustafson 14-May-14 15:41pm    
First go into your code where you want to place a breakpoint (the place where execution will stop). Click in the margin to the left of the code. A red dot will appear and the code line will be highlighted in red. Make sure that the Solution Configuration dropdown shows "Debug". Now press F5. The program will rebuild and start executing. It will stop when execution "hits" the breakpoint.

For more detailed information, Google "Visual Studio debugging".
gggustafson 14-May-14 15:44pm    
I think your algorithm is strange. See kombsh answer at http://stackoverflow.com/questions/16606753/populating-a-dataset-from-a-csv-file.

1 solution

Fixed it thank you for all the help and effort.

it occurs to be that my Algorithm '(the way of saving)' wasnt optional, so i re-coded it and i figured it out why it did so, (thanks to debugging 'Breakpoint').

This is the fix i've came up with that solved it;

C#
// Column headers
 string columnsHeader = "";
 for (int i = 0; i < dataGridView1.Columns.Count; i++)
 {
     if (i != dataGridView1.Columns.Count - 1)
     {
         columnsHeader += dataGridView1.Columns[i].Name + ",";
     }
     else
     {
         columnsHeader += dataGridView1.Columns[i].Name;
     }
 }
 sb.Append(columnsHeader + Environment.NewLine);

 // Go through each cell in the datagridview
 for (int q = 0; q < dataGridView1.RowCount; q++)
 {
     // Make sure it's not an empty row.
     for (int c = 0; c < dataGridView1.Rows[q].Cells.Count; c++)
     {
         if (c != dataGridView1.Rows[q].Cells.Count - 1)
         {
             // Append the cells data followed by a comma to delimit.
             sb.Append(dataGridView1.Rows[q].Cells[c].Value + ",");
         }
         else
         {
             sb.Append(dataGridView1.Rows[q].Cells[c].Value);
         }
     }
     // Add a new line in the text file.
     if (q != dataGridView1.RowCount - 1) sb.Append(Environment.NewLine);
 }


thank you all so much :)
 
Share this answer
 

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