Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#2.0 Windows
Hi developer's
I am loading a csv file in dataset and visualize them in datagridview and after applied some operation on data , i am save a datagridview values again in csv file format.
 

but from some time my csv file not save csv file in correct format because values from the cell are fall to the another cells
for example
if in a orignal csv file values at [0] index location, after save this file from datagridview values fall at the [3] index location .
 
and given some unknown type of values , I do not know Because my orignal csv file not cantain this type values
 
"PASI ID : < 10441494957439>
"
please check my code .
  public void DataExport()
        {
            try
            {
                string strColumn = string.Empty;
                string strRow = string.Empty;
                StringBuilder objSB = new StringBuilder();
                for (int i = 0; i < Datagidveiw1.Columns.Count; i++)
                {
                    strColumn += (i >= Datagidveiw1.Columns.Count - 1) ? Datagidveiw1.Columns[i].Name : Datagidveiw1.Columns[i].Name + ",";
                }
                objSB.AppendLine(strColumn);
 
                for (int i = 1; i < Datagidveiw1.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < Datagidveiw1.Columns.Count; j++)
                    {
                        strRow += (j >= Datagidveiw1.Columns.Count - 1) ? Datagidveiw1.Rows[i].Cells[j].Value.ToString().Replace("\n", "") : Datagidveiw1.Rows[i].Cells[j].Value.ToString().Replace("\n", "") + ",";
                    }
                    objSB.AppendLine(strRow);
                    strRow = string.Empty;
                }
                File.AppendAllText(Locations.Text, objSB.ToString());
                Datagidveiw1.Refresh();
               
                MessageBox.Show("Data save sucessfull");
                Application.Exit();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void save_Click(object sender, EventArgs e)
        {
            
            try
            {
                SaveFileDialog SaveDialogbox = new SaveFileDialog();
                SaveDialogbox.FileName = Locations.Text;
                SaveDialogbox.Filter = "Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
                SaveDialogbox.FilterIndex = 1;
                SaveDialogbox.RestoreDirectory = true;
                DialogResult Dialogresult1 = SaveDialogbox.ShowDialog();
                if (Dialogresult1 == DialogResult.OK)
                {
                    Locations.Text = SaveDialogbox.FileName;
                    DataExport();
                    Application.DoEvents();
                }
                 else
                 {
                 MessageBox.Show("Invalid Arguments");
                }
}}
 
please check this code,
thanks
Posted 22-Dec-10 20:22pm
Edited 22-Dec-10 20:23pm
v2
Comments
Hiren Solanki at 23-Dec-10 2:23am
   
Always prefer to wrap code in 'pre' tag.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Hi Vishu,
 
Get the objSB.ToString()in quick watch and try to save directly in notepad in CSV format so you can able to visible those character and string extra, need to removed form string.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

I would approach this slightly differently.
 
To generate the column names, I would use the original DataSet. Instead of using a for loop I would a foreach loop they ahve less over head then the for loops
 
eg.
 
let's assume that your dataset is called ds.
 
StringBuilder sb = new Stringbuilder();
 
int numColumns = Tables[0].Columns.Count-1 //-1 is for zero based count
int columnCounter= numColumns;
 
foreach(DataColumn dc in ds.Tables[0].Columns)
{
    sb.Append(dc.ColumnName);
    AppendDelimiter(sb, ref columnCounter);
}
 

 
foreach(GridViewRow gvr in Datagidveiw1.Rows)
{
   columnCounter=numColumns
   foreach(TableCell c in grv.Cells)
   {
       sb.Append(c.Text)
       AppendDelimiter(sb,ref columnCounter);
   }
}
 

private void AppendDelimiter(StringBuilder sb, ref int columnCounter)
{
       if (columnCounter > 0)
         sb.Append(';');
       else
         sb.Append(Environment.NewLine);
 
       columnCounter--;
}
do the rest of the code here to write content to file.
 
I have tested this and it worked just fine.
 
If you have any more issues then I would like to see the code that you use to construct your gridview and or a screenshot of the populated gridview.
 
Another alternative is to persit your changes in the gridview to the DataSet and then iterate through the DataSet.Table[0].Rows to create the csv.
  Permalink  
v4
Comments
Ben Fair at 28-Dec-10 10:43am
   
Foreach has more overhead and does not perform as well as a for loop.
sucram at 29-Dec-10 2:24am
   
Hi Ben,
 
When using the Foreach loop with an array it has nor performance hit what so ever. Many abide to this vicious rumor.
 
If you however use the foreach loop with lists then you will suffer a blow to performance. This blow is not significant if you do not work with list often. If you do however need to access lists often then the foreach loop should be replaced with a for loop.

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



Advertise | Privacy | Mobile
Web02 | 2.8.140709.1 | Last Updated 28 Dec 2010
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid