1

Can anybody help me understand what these lines of codes really means...i understand it but not exactly...i mean what foreach is exactly doing here???

if (dt.Rows.Count > 0)
    {
        //GridView1.Visible = true;
        Gridview1.DataSource = dt;
        Gridview1.DataBind();
        StringBuilder sb = new StringBuilder();

        foreach (DataColumn col in dt.Columns)
        {
            sb.Append(col.ColumnName + ",");
        }

        sb.Remove(sb.Length - 1, 1);
        sb.Append(Environment.NewLine);

        foreach (DataRow row in dt.Rows)
        {
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sb.Append(row[i].ToString() + ",");
            }

            sb.Append(Environment.NewLine);
        }

        Response.ClearHeaders();
        Response.AppendHeader("Content-Disposition", "attachment; filename=CDR OF " + TextBox1.Text + ".csv");
        Response.AppendHeader("Content-Length", sb.Length.ToString());
        Response.ContentType = "text/csv";
        Response.Write(sb.ToString());
        Response.Flush();
        Response.End();
    }
    else
    {
        //GridView1.Visible = false;
        Show("No CDR Found!");
    }

And can we use StringWriter or string in place of StringBuilder ???

Mridul Koul
  • 120
  • 11
  • 1
    first `foreach`: iterating through the columns and adding the column names to `sb`. second `foreach`: iterating through the rows – bansi Apr 06 '16 at 06:07
  • 1
    Well, [foreach](https://msdn.microsoft.com/library/ttw7t8t6.aspx) itself should be a very simple to understand concept. You have some "things" and want to do something *for each* one of those "things". Now, exactly *what* you are doing inside can range from very simple to very complicated stuff. In both of your cases, you basically gather data and building a string, containing all the data. This is what `StringBuilder` was created for. You *could* use a `string`, but each time you add something to an existing `string`, you create a new one, which would be bad. – Corak Apr 06 '16 at 06:12

4 Answers4

1

The first foreach is appending the column header names. The second is appending the cell values. Both in comma separated way. Ao you are converting a GridView to a csv.

Why don't use a simple converter like the CSV helper. Has everything you need. CSV Helper

Franki1986
  • 1,320
  • 1
  • 15
  • 40
  • 1
    @MridulKoul - you *could* use a `string`, but that would have a major impact on performance. See http://stackoverflow.com/questions/73883/string-vs-stringbuilder for example for further information. – Corak Apr 06 '16 at 06:17
1

Looks like the code is trying to generate csv file with headers for the data table. The first for each loops through the columns in DataTable and generates a comma separated column name string (referred by StringBuffer).

 sb.Remove(sb.Length - 1, 1);
 sb.Append(Environment.NewLine);

The above code snippet removes the last comma from the comma separated column name string and then adds a new line

 foreach (DataRow row in dt.Rows)
    {
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sb.Append(row[i].ToString() + ",");
        }

        sb.Append(Environment.NewLine);
    }

the loop above iterates through each row of DataTable, and creates a comma separated string for each column value of the. After each row is processed, a new line is added so that the next row contents are added as comma separated string in new line.

Vineet Desai
  • 872
  • 5
  • 16
1
  1. The first loop lists all your column names with a comma:

colname1,colname2,colname3,

  1. The Remove then removes the last comma and adds a newline

colname1,colname2,colname3\n

  1. The second loop lists all your values of each column of each row

colname1,colname2,colname3\n row1col1value,row1col2value,row1col3value,\n -- note that the comma is NOT removed here row2col1value,row2col2value,row2col3value,\n row3col1value,row3col2value,row3col3value,\n row4col1val etc...

And yes, I think you can use a string instead of the string builder.

Tjab
  • 368
  • 1
  • 4
  • 18
  • why comma is removed in coloumn section and not removed in rows section...? – Mridul Koul Apr 06 '16 at 06:19
  • 2
    Because a line like `sb.Remove(sb.Length - 1, 1);` (i.e. "remove the last character" or more precisely "start at the position in `sb` that is one less than its length and remove one character") is missing in the second `foreach`. Now **why** it is missing, we cannot tell. It *might* be a bug. – Corak Apr 06 '16 at 06:20
  • if it remove comma separating columns..does it make any diffrence...i mean i tried removing sb.Remove(sb.Length - 1, 1); ....but the downloaded csv file doesnt seems to be changed a bit... – Mridul Koul Apr 06 '16 at 06:30
  • 1
    In CSV, `"data,data,data,"` indicates that there are *four* columns (the last one is empty), while `"data,data,data"` (note the missing last comma) indicates that there are *three* columns. Now if this is a big deal or not completely depends on how the CSV is read back in again. – Corak Apr 06 '16 at 06:38
  • Not sure how, but I accentually down voted this answer and cannot redo the action... – Kilise Apr 07 '16 at 17:33
1

The first loop is taking each column name from Datatable and appending with a separator comma to a stringBuilder. Then it is trimming the last comma appended and adding a new line to it. The second loop is taking all the data values of DataRow(row by row) , then comma and appending to the same stringbuilder.