views:

115

answers:

1

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.

A: 

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)

Thomas Levesque
Thomas,Thanks for the answer. I was doing on the same lines and accidentally found this event on the "richTextBox1_TextChanged" and within this event I added this line of code "richTextBox1.Text = richTextBox1.Text.Replace("~", "\n");". And also made the control read only so that the user cannot make changes to the text within it and fire the TextEvent_Changes event. Do you think this approach is ok/better/bad?Thanks again for your Input.Ranjit
Ranjit
You shouldn't change the Text property explicitly, because it will update the data source through the binding... The Format and Parse events are designed exactly for what you're trying to do
Thomas Levesque