Fyah10
Fyah10

Reputation: 49

problems with the replace method in C#

I am developing an application in C# that generates a CSV files from a MySql database. The problem I have is that when the PDF file is generated, the dates have this format "dd/MM/yyyy" and what I want is to have a format like this "dd-MM-yyyy", thats why inside the for loop of the rows I do a "replace" and I say:

for (int j = 0; j < columnCount; j++)
{
    outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString().Replace('/', '-') + ";";
    
    if (j == 9 ) //position of the column to be modified
    {
        outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString().Replace('-','/') + ";";
    }
}

the rest of the code is this:

private void btnexport_Click(object sender, EventArgs e)
{
    if (dataGridView2.Rows.Count > 0)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "CSV (*.csv)|*.csv";
        bool fileError = false;
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            if (File.Exists(sfd.FileName))
            {
                try
                {
                    File.Delete(sfd.FileName);
                }
                catch (IOException ex)
                {
                    fileError = true;
                    MessageBox.Show("No se pueden escribir los datos" + ex.Message);
                }
            }
            if (!fileError)
            {
                try
                {
                    int columnCount = dataGridView2.Columns.Count;
                    string columnNames = "";
                    string[] outputCsv = new string[dataGridView2.Rows.Count +1];
                    for (int i = 0; i < columnCount; i++)
                    {
                        columnNames += dataGridView2.Columns[i].HeaderText.ToString()+";";
                    }
                    outputCsv[0] += columnNames;
                    
                    for (int i = 1; i < dataGridView2.Rows.Count; i++)
                    {
                        for (int j = 0; j < columnCount; j++)
                        {
                            // first I replace in the whole file the "/" by "-"   
                            outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString().Replace('/', '-') + ";";
                        
                            if (j == 9 ) 
                            {
                                //then I go to position 6 and change ('-','/') as the format of that field must necessarily have the slash ("/")
                                outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString().Replace('-','/') + ";";
                            }
                        }
                    }
                    File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
                    MessageBox.Show("Fichero generado correctamente", "Atencion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error :" + ex.Message);
                }
            }
        }
    }
    else
    {
        MessageBox.Show("Debes seleccionar unas cuentas", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
        MessageBox.Show("No se ha generado un reporte!!!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

result:

REFERENCE;LAWYER;PORTFOLIO_NAME;CUT_OFF_DATE;PORTFOLIO_NUMBER;NAME;COURT_NUMBER;COURT_CITY;PROCESS_TYPE;COURT_CASE;CONSIGATION_ACCOUNT;
16437;Sara;ADWS;01-01-1900 0:00:00;1;BANK PEN;1;MARTORELL;ETJ;0331-12;0331/12;0782000005033112;
14572;Sara;MLSK;01-01-1900 0:00:00;1;BANK PEN;1;BADALONA;ETJ;4598-16;4598/16;0782000005031897;

expected:(As we can see, this is repeated twice with the correct and with the incorrect format ("0331-12;0331/12"))

REFERENCE;LAWYER;PORTFOLIO_NAME;CUT_OFF_DATE;PORTFOLIO_NUMBER;NAME;COURT_NUMBER;COURT_CITY;PROCESS_TYPE;COURT_CASE;CONSIGATION_ACCOUNT;
    16437;Sara;ADWS;01-01-1900 0:00:00;1;BANK PEN;1;MARTORELL;ETJ;0331/12;0782000005033112;
    14572;Sara;MLSK;01-01-1900 0:00:00;1;BANK PEN;1;BADALONA;ETJ;4598/16;0782000005031897;

What am I doing wrong??? Thankssss!!

Upvotes: 2

Views: 134

Answers (2)

smoore4
smoore4

Reputation: 4866

In your iteration you can use TryParse to make the original string into a date and then format the date in a subsequent ToString().

DateTime date1;
DateTime.TryParse(dataGridView2.Rows[i - 1].Cells[j].Value.ToString(), out date1);
outputCsv[i] += date1.ToString("dd-MM-yyyy", DateTimeFormatInfo.InvariantInfo);

Upvotes: 1

Rafalon
Rafalon

Reputation: 4515

Simply check if your value is a DateTime and format it accordingly:

if (dataGridView2.Rows[i - 1].Cells[j].Value is DateTime date)
{
    outputCsv[i] += date.ToString("dd-MM-yyyy H:mm:ss") + ";";
}
else
{
    outputCsv[i] += dataGridView2.Rows[i - 1].Cells[j].Value.ToString() + ";";
}

Below is a sample to show the principle:

using System;
class HelloWorld {
    static void Main() {
        object[] test = { DateTime.Now, "fizzbuzz" };
        
        foreach(var t in test)
        {
            if(t is DateTime date)
            {
                Console.WriteLine(date.ToString("dd-MM-yyyy H:mm:ss"));
            }
            else
            {
                Console.WriteLine("Not a DateTime");
            }
        }
    }
}

Writes:

11-08-2021 13:02:20
Not a DateTime

Check it online

Upvotes: 2

Related Questions