Rich Text Box. .NET 2.0 Content formatting

.netrichtextbox

I have a small windows client application data bound to a single table backend.
I created a DataSet using the wizard in VS 2005, and it automatically create the underlying adapter and a GridView. I also have a RichText control and bound it to this DataSet. All well so far but, I need to replace certain characters(~) on the fly before the data is shown in the RichTextbox. Can this be done.

Best Solution

You need to handle the Format and Parse events of the Binding.

Binding richTextBoxBinding = richTextBox.DataBindings.Add("Text", bindingSource, "TheTextColumnFromTheDatabase");
richTextBoxBinding.Format += richTextBoxBinding_Format;
richTextBoxBinding.Parse += richTextBoxBinding_Parse;

In the Format event, convert the internal value to the formatted representation :

private void richTextBoxBinding_Format(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(string))
        return; // this conversion only makes sense for strings

    if (e.Value != null)
        e.Value = e.Value.ToString().Replace("~", "whatever");
}

In the Parse event, convert the formatted representation to the internal value :

private void richTextBoxBinding_Parse(object sender, ConvertEventArgs e)
{
    if (e.DesiredType != typeof(string))
        return; // this conversion only makes sense for strings (or maybe not, depending on your needs...)

    if (e.Value != null)
        e.Value = e.Value.ToString().Replace("whatever", "~");
}

Note that you only need to handle the Parse event if your binding is two-way (i.e. the user can modify the text and the changes are saved to the database)

Related Question