title: Exported gridview to csv is empty
body: <p>I would like to export my Gridview to a csv file by clicking on the button "<strong><em>RunSimulationButton</em></strong>". However, it seems that my current code only exports the column names, but doesn't export the cell contents of the gridview.</p>
  
  <p>Any help would be appreciated! Thank you! (P.S: I am a beginner at ASP.NET)</p>
  
  <p>Here is my code:</p>
  
  <p><strong>ASPX</strong></p>
  
  <pre><code>&lt;asp:GridView ID="InflationGridView" runat="server" AutoGenerateColumns="False" Width="52%"
                                              ShowHeaderWhenEmpty="True" CellPadding="4" ForeColor="#333333" GridLines="None"
                                              AllowSorting="True" ShowFooter="True"&gt;
                                              &lt;AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" /&gt;
                                              &lt;Columns&gt;
                                                  &lt;asp:TemplateField HeaderText="Start Year"&gt;
                                                      &lt;ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" /&gt;
                                                      &lt;ItemTemplate&gt;
                                                          &lt;asp:TextBox ID="StartInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"&gt;&lt;/asp:TextBox&gt;
                                                          &lt;asp:NumericUpDownExtender ID="StartInflationNumericUpDownExtender" runat="server"
                                                              TargetControlID="StartInflationTextBox" Minimum="0" Width="60"&gt;
                                                          &lt;/asp:NumericUpDownExtender&gt;
                                                      &lt;/ItemTemplate&gt;
                                                  &lt;/asp:TemplateField&gt;
                                                  &lt;asp:TemplateField HeaderText="End Year"&gt;
                                                      &lt;ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" /&gt;
                                                      &lt;ItemTemplate&gt;
                                                          &lt;asp:TextBox ID="EndInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"&gt;&lt;/asp:TextBox&gt;
                                                          &lt;asp:NumericUpDownExtender ID="EndInflationNumericUpDownExtender" runat="server"
                                                              TargetControlID="EndInflationTextBox" Minimum="1" Width="60"&gt;
                                                          &lt;/asp:NumericUpDownExtender&gt;
                                                      &lt;/ItemTemplate&gt;
                                                  &lt;/asp:TemplateField&gt;
                                                  &lt;asp:TemplateField HeaderText="Inflation Rate"&gt;
                                                      &lt;ItemStyle Font-Size="13px" Width="25%" HorizontalAlign="Center" Height="2px" /&gt;
                                                      &lt;ItemTemplate&gt;
                                                          &lt;asp:TextBox ID="InflationTextBox" runat="server" Text="" Width="60px" Style="text-align: center;"&gt;&lt;/asp:TextBox&gt;
                                                          %
                                                      &lt;/ItemTemplate&gt;
                                                      &lt;FooterStyle HorizontalAlign="Right" /&gt;
                                                      &lt;FooterTemplate&gt;
                                                          &lt;asp:Button ID="AddNewInflationRowButton" runat="server" Text="Add New Row" OnClick="AddNewInflationRowButton_Click"
                                                              Height="25px" /&gt;
                                                      &lt;/FooterTemplate&gt;
                                                  &lt;/asp:TemplateField&gt;
                                              &lt;/Columns&gt;
                                              &lt;FooterStyle Font-Bold="True" ForeColor="White" Height="20px" /&gt;
                                              &lt;HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /&gt;
                                              &lt;PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /&gt;
                                              &lt;RowStyle BackColor="#F7F6F3" ForeColor="#333333" /&gt;
                                              &lt;SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" /&gt;
                                              &lt;SortedAscendingCellStyle BackColor="#E9E7E2" /&gt;
                                              &lt;SortedAscendingHeaderStyle BackColor="#506C8C" /&gt;
                                              &lt;SortedDescendingCellStyle BackColor="#FFFDF8" /&gt;
                                              &lt;SortedDescendingHeaderStyle BackColor="#6F8DAE" /&gt;
                                          &lt;/asp:GridView&gt;
  &lt;asp:Button ID="RunSimulationButton" runat="server" Text="Run Simulation" OnClick="RunSimulationButton_OnClick" /&gt;
  </code></pre>
  
  <p><strong>ASPX.cs</strong></p>
  
  <pre><code>    protected void Page_Load(object sender, EventArgs e)
      {
          if (!Page.IsPostBack)
          {
              FirstInflationGridViewRow();
          }
  
  
      }
  
  
      // Display first row of the GridView
      protected void FirstInflationGridViewRow()
      {
          DataTable table = new DataTable();
          DataRow dr = null;
  
          table.Columns.Add(new DataColumn("Col1", typeof(int)));
          table.Columns.Add(new DataColumn("Col2", typeof(int)));
          table.Columns.Add(new DataColumn("Col3", typeof(double)));
  
          dr = table.NewRow();
  
          dr["Col1"] = DBNull.Value;
          dr["Col2"] = DBNull.Value;
          dr["Col3"] = DBNull.Value;
  
          table.Rows.Add(dr);
  
          ViewState["currentInflationTable"] = table;
          InflationGridView.DataSource = table;
          InflationGridView.DataBind();
      }
  
  
  
      // Button to add rows to the GridView
      protected void AddNewInflationRowButton_Click(object sender, EventArgs e)
      {
          AddNewInflationRow();
      }
  
      private void AddNewInflationRow()
      {
          int rowIndex = 0;
  
          if (ViewState["currentInflationTable"] != null)
          {
              DataTable dtCurrentTable = (DataTable)ViewState["currentInflationTable"];
              DataRow drCurrentRow = null;
              if (dtCurrentTable.Rows.Count &gt; 0)
              {
                  for (int i = 1; i &lt;= dtCurrentTable.Rows.Count; i++)
                  {
                      TextBox TextBoxStart =
                        (TextBox)InflationGridView.Rows[rowIndex].Cells[0].FindControl("StartInflationTextBox");
                      TextBox TextBoxEnd =
                        (TextBox)InflationGridView.Rows[rowIndex].Cells[1].FindControl("EndInflationTextBox");
                      TextBox TextBoxInflation =
                        (TextBox)InflationGridView.Rows[rowIndex].Cells[2].FindControl("InflationTextBox");
  
                      drCurrentRow = dtCurrentTable.NewRow();
  
                      int Num;
                      bool isNumStart = String.IsNullOrEmpty(TextBoxStart.Text.ToString()) ? true : int.TryParse(TextBoxStart.Text.ToString(), out Num);
                      bool isNumEnd = String.IsNullOrEmpty(TextBoxEnd.Text.ToString()) ? true : int.TryParse(TextBoxEnd.Text.ToString(), out Num);
                      bool isNumInflation = String.IsNullOrEmpty(TextBoxInflation.Text.ToString()) ? true : int.TryParse(TextBoxInflation.Text.ToString(), out Num);
  
                      if (!isNumStart || !isNumEnd || !isNumInflation)
                      {
                          this.ErrorInflationLabel.Text = "Incorrect input(s). All fields must be numeric.";
                          ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                          this.ErrorInflationLabel.Visible = true;
                          this.InflationErrorUpdatePanel.Update();
                          return;
  
                      }
                      else if ((TextBoxStart.Text == "") || (TextBoxEnd.Text == "") || (TextBoxInflation.Text == ""))
                      {
                          this.ErrorInflationLabel.Text = "All fields must be completed.";
                          ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                          this.ErrorInflationLabel.Visible = true;
                          this.InflationErrorUpdatePanel.Update();
                          return;
  
                      }
                      else if (TextBoxEnd.Text == HorizonTextBox.Text)
                      {
                          this.ErrorInflationLabel.Text = "Cannot set inputs beyond investment horizon.";
                          ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                          this.ErrorInflationLabel.Visible = true;
                          this.InflationErrorUpdatePanel.Update();
                          return;
                      }
                      else
                      {
                          this.ErrorInflationLabel.Text = "";
                          this.InflationErrorUpdatePanel.Update();
                          dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxStart.Text;
                          dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxEnd.Text;
                          dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxInflation.Text;                           
                          rowIndex++;
                      }
                  }
  
  
                  dtCurrentTable.Rows.Add(drCurrentRow);
                  dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Col1"] = (Convert.ToDouble(dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 2]["Col2"]) + 1).ToString();
                  dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Col2"] = HorizonTextBox.Text;
  
                  ViewState["currentInflationTable"] = dtCurrentTable;
  
                  InflationGridView.DataSource = dtCurrentTable;
                  InflationGridView.DataBind();
              }
          }
          else
          {
              Response.Write("ViewState is null");
          }
          SetPreviousInflationData();
      }
  
      // Set data in previous rows when new row is added
      private void SetPreviousInflationData()
      {
          int rowIndex = 0;
          if (ViewState["currentInflationTable"] != null)
          {
              DataTable dt = (DataTable)ViewState["currentInflationTable"];
              if (dt.Rows.Count &gt; 0)
              {
                  for (int i = 0; i &lt; dt.Rows.Count; i++)
                  {
                      TextBox TextBoxStart = (TextBox)InflationGridView.Rows[rowIndex].Cells[0].FindControl("StartInflationTextBox");
                      TextBox TextBoxEnd = (TextBox)InflationGridView.Rows[rowIndex].Cells[1].FindControl("EndInflationTextBox");
                      TextBox TextBoxInflation =
                        (TextBox)InflationGridView.Rows[rowIndex].Cells[2].FindControl("InflationTextBox");
  
                      TextBoxStart.Text = dt.Rows[i]["Col1"].ToString();
                      TextBoxEnd.Text = dt.Rows[i]["Col2"].ToString();
                      TextBoxInflation.Text = dt.Rows[i]["Col3"].ToString();
                      rowIndex++;
                  }
              }
          }
      }
  
  
   //************************* EXPORT TO CSV BY CLICKING ON SIMULATION BUTTON
  
      protected void retrieveInflationData()
      {
          if (Session["currentInflationTable"] != null)
          {
              DataTable dt = (DataTable)Session["currentInflationTable"]; ;
  
              if ((dt != null) &amp;&amp; (dt.Rows.Count &gt; 0))
              {
                  InflationGridView.Visible = true;
                  InflationGridView.DataSource = dt;
                  InflationGridView.DataBind();
              }
              else
              {
                  InflationGridView.Visible = false;
              }
          }
      }
  
      protected void RunSimulationButton_OnClick(object sender, EventArgs e)
      {
          retrieveInflationData();
          StreamWriter sw = new StreamWriter("C:\inst_research\MonteCarlo\gridview.csv");
          // now add the gridview header in csv file suffix with "," delimeter except last one
          for (int i = 0; i &lt; InflationGridView.Columns.Count; i++)
          {
              sw.Write(InflationGridView.Columns[i].HeaderText);
              if (i != InflationGridView.Columns.Count)
              {
                  sw.Write(",");
              }
          }
          // add new line
          sw.Write(sw.NewLine);
          // iterate through all the rows within the gridview
          foreach (GridViewRow dr in InflationGridView.Rows)
          {
              // iterate through all colums of specific row
              for (int i = 0; i &lt; InflationGridView.Columns.Count; i++)
              {
                  // write particular cell to csv file
                  string test = dr.Cells[i].Text;
                  sw.Write(dr.Cells[i].Text);
                  if (i != InflationGridView.Columns.Count)
                  {
                      sw.Write(",");
                  }
              }
              // write new line
              sw.Write(sw.NewLine);
          }
          // flush from the buffers.
          sw.Flush();
          // closes the file
          sw.Close();
      }
  </code></pre>