0

I want to remove the last (empty) row of a StringBuilder Object

EDIT: The empty row is from the "AllowUserToAddRows" how can i skip it?

  • c# Forms application
  • dataGridView1 on form2
  • I want Export to CSV (separated by semicolon) [btw. it's just one column]
  • It Could happen, that a previously created CSV is parsed to the dataGridView again

I use a altered solution from here: Exporting datagridview to csv file

my code

void SaveDataGridViewToCSV(string filename)
{
    var sb = new StringBuilder();

    var headers = dataGridView1.Columns.Cast<DataGridViewColumn>();
    sb.AppendLine(string.Join(";", headers.Select(column => "" + column.HeaderText + ";").ToArray()));

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        var cells = row.Cells.Cast<DataGridViewCell>();
        sb.AppendLine(string.Join(";", cells.Select(cell => "" + cell.Value + ";").ToArray()));
    }

    try
    {
        File.WriteAllText(filename, sb.ToString());
    }
    catch (Exception exceptionObject)
    {
        MessageBox.Show(exceptionObject.ToString());
    }
}

The sb.ToString looks like this {Coumn;90;90;626;626;;}

The "real" StringBuilder Object as String is: {Coumn;\r\n90;\r\n90;\r\n626;\r\n626;\r\n;}

I want to remove the empty last row.

I tried to parse the stringbuilder to a string, and then remove last semicolon but with no success (i have problem with the End Of Line.)

string s = sb.ToString();
while (s.EndsWith(";\r\n;") == true)
{
    s.Substring(0, s.Length - 5);
}

I tried to remove last element of array, but StingBuilder is no array

I'm stuck.

cuilster
  • 123
  • 1
  • 12

1 Answers1

0

As i found out the empty set is always exported to the csv. It's from the ability that the user can input data to the dataGridView, and there is always a empty, active row.

if i disable dataGridView1.AllowUserToAddRows the empty row for userinput is not within the stringbuilder set of data.

   void SaveDataGridViewToCSV(string filename)
    {
        var sb = new StringBuilder();

        //SOLUTION disable AllowUserInput to avoid empty set saved to CSV
        dataGridView1.AllowUserToAddRows = false;

        var headers = dataGridView1.Columns.Cast<DataGridViewColumn>();
        sb.AppendLine(string.Join(";", headers.Select(column => "" + column.HeaderText + ";").ToArray()));

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            var cells = row.Cells.Cast<DataGridViewCell>();
            sb.AppendLine(string.Join(";", cells.Select(cell => "" + cell.Value + ";").ToArray()));
        }

        try
        {
            File.WriteAllText(filename, sb.ToString());
        }
        catch (Exception exceptionObject)
        {
            MessageBox.Show(exceptionObject.ToString());
        }
    }

thanks for help!

cuilster
  • 123
  • 1
  • 12