1

I'm a little confused with the following code. I'm taking plain text stored in a database and supplying it to the Text portion of a RichTextBox control then saving it to a file.

The first file is always blank even though it does contain data.

RichTextBox test = new RichTextBox();
for(int i = 0; i < dt.Rows.Count; i++)
{
     test.Text = dt.Rows[i][1].ToString();
     string FILE_NAME = Path.Combine(path, dt.Rows[i][0].ToString() + ".rtf");
     test.SaveFile(FILE_NAME, RichTextBoxStreamType.RichText);
     test.Clear();
}

Now currently for a work around even though it's ugly I did the following and it does write the first entry to a file correctly

bool run_once = true;
RichTextBox test = new RichTextBox();
for(int i = 0; i < dt.Rows.Count; i++)
{
     test.Text = dt.Rows[i][1].ToString();
     string FILE_NAME = Path.Combine(path, dt.Rows[i][0].ToString() + ".rtf");
     test.SaveFile(FILE_NAME, RichTextBoxStreamType.RichText);
     test.Clear();

     if (run_once)
     {
          File.Delete(FILE_NAME);
          run_once = false;
          i--;
     }
}

Could someone shed some light here?

Tsukasa
  • 6,342
  • 16
  • 64
  • 96
  • 1
    This may help: http://stackoverflow.com/questions/10725438/converting-txt-to-rtf – DSway Sep 24 '13 at 15:37
  • Using the code I have formats plain text into rtf formatting. That works but the above loop always writes the first file with no data at all. When I delete it in the work around and run that entry through again it writes the file correctly. – Tsukasa Sep 24 '13 at 15:41
  • If you want to use the RichTextBox, LarsTech has a solution below. Since you don't really need an actual control, I think a method that just converts to rtf may be faster. – DSway Sep 24 '13 at 16:17

1 Answers1

1

Interesting. I "think" it might be a bug. This was my work-around:

using (RichTextBox test = new RichTextBox()) {
  for (int i = 0; i < dt.Rows.Count; i++) {
    test.SelectAll();
    test.Text = dt.Rows[i][1].ToString();
    string FILE_NAME = Path.Combine(path, dt.Rows[i][0].ToString() + ".rtf");
    test.SaveFile(FILE_NAME, RichTextBoxStreamType.RichText);
    test.Clear();
  }
}

The SelectAll() was needed to make the bug go away. Not sure why.

LarsTech
  • 80,625
  • 14
  • 153
  • 225