Tsukasa
Tsukasa

Reputation: 6552

Saving plain text to RichText

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?

Upvotes: 1

Views: 279

Answers (1)

LarsTech
LarsTech

Reputation: 81610

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.

Upvotes: 1

Related Questions