0
votes

I am trying to put some Rich Text Formatted (RTF) text into a Rich Text Box (RTB). I am iterating through several winform controls to grab the RTB I need. I can use the RichTextBox.Text property to add normal text to the text box, however when I try to use the RichTextBox.Rtb property to add RTF text to it I get an error saying it doesn't exist for that control ("Control does not contain a definition for Rtb). In the code example below, why doesn't my "rtbControl" have the Rtb property even though the control should be a RichTextBox? How can I use the Rtb property / set RTF text for this control?

    // RTF string I want to display in the RTB
    string some_rtb_text = @"{\rtf1\ansi This is some \b bold\b0 text.}";  
            foreach (Control rtbControl in GlobalVars.myUserControl1.Controls)  // iterate through all the controls and find the one I want
            {
                if (rtbControl is RichTextBox & rtbControl.Name == "the_text_box_I_want_to_use")  // Making sure the control is a RichTextBox
                {
                    rtbControl.Rtb = some_rtb_text;  // it's telling me that rtbControl does not contain a definition for Rtb
                }
            }

   
2

2 Answers

1
votes

In the if statement it checks if rtbControl is a RichTextBox. If it is, you need to create a new RichTextBox variable to be able to use RichTextBox properties such as Rtf or SelectedRTF.

if (rtbControl is RichTextBox & rtbControl.Name == "name_of_control")  // Making sure the control is a RichTextBox
   {
        RichTextBox rtb = rtbControl as RichTextBox;
        rtb.Rtf = some_rtb_text;
   }
2
votes

Rhys Wootton's answer is correct and IMHO answers your question, but can be simplified a bit:

if (rtbControl.Name == "name_of_control" && rtbControl is RichTextBox rtb)
{
    rtb.Rtf = some_rtb_text;
}