Error writing a file using SqlDataReader

2

I am using datagridview to show my table data and I have to create a file with this data, I tried to make the code that I will post below but using (SqlDataReader sqlReader = comm.ExecuteReader()) is stopping my program. I have no error, it just for running the program.

SqlCommand comm = new SqlCommand();
comm.Connection = new SqlConnection(@"Data source = *** ; Database=*** ; User Id=*** ; Password=***");
comm.Connection.Open();
if (dataGridViewEnviarDados.SelectedRows.Count > 0)
{
 MessageBox.Show("inicio");
 foreach (DataGridViewRow r in dataGridViewEnviarDados.SelectedRows)
 {
  MessageBox.Show("datagrind");
  var transactionHandler = new TransactionHandler();
  FileInfo arquivo = new FileInfo(@"C:\Users\HP8200\Desktop\faturas\" + r.Cells[0].Value.ToString() + r.Cells[1].Value.ToString() + r.Cells[2].Value.ToString() + ".txt");
  using (StreamWriter tw = new StreamWriter(arquivo.FullName, false, Encoding.Default))
  {
   MessageBox.Show("streamwriter");
   String sql = @"SELECT  X.TransDocument, X.TransSerial,X.TransDocNumber, I.CreateDate, I.PartyFederalTaxID, I.TotalAmount, I.ShipToAddressDetailLine1, I.ShipToPostalCode, U.ItemID, U.TotalGrossAmount, U.TotalNetPrintAmout, U.Quantity, Y.ItemID, Y.BarCode, Y.TaxableGroupID FROM SaleTransaction I INNER JOIN ELISAData.dbo.SaleTransactionDetails U ON I.TransDocNumber = U.TransDocNumber INNER JOIN ELISAData.dbo.UXMenu X ON U.TransDocNumber = X.TransDocNumber INNER JOIN ELISAData.dbo.Item Y ON U.ItemID = Y.ItemID WHERE X." + r.Cells[2].Value.ToString() + " = U.TransDocNumber AND U.TransDocNumber = I.TransDocNumber AND U.ItemID = Y.ItemID Order by TransDocNumber";
   MessageBox.Show("erro 1");
   comm.CommandText = sql;
   MessageBox.Show("erro 2");
   /*SqlCommand comm = new SqlCommand();
   comm.Connection = new SqlConnection(@"Data source = 2c4138928627\Sage ; Database=ELISAData ; User Id=sa ; Password=sage2008+");
   comm.CommandText = sql;
   comm.Connection.Open();
   */
   foreach (DataGridViewColumn c in dataGridViewEnviarDados.Columns)
   {
    MessageBox.Show("erro 3");
    using (SqlDataReader sqlReader = comm.ExecuteReader())
    {
     MessageBox.Show("erro 4");
     while (sqlReader.Read())
     {
      tw.WriteLine(sqlReader["PartyFederalTaxID"] + ";" + sqlReader["TransSerial"] + sqlReader["TransDocNumber"] + ";" + sqlReader["CreateDate"] + ";" + sqlReader["TotalAmount"]);
     }
    }
   }
  }
 }
}
    
asked by anonymous 29.08.2017 / 18:51

0 answers