How to access RichTextBox.Select() method while referring to it as a "Control"

StackOverflow https://stackoverflow.com/questions/22158256

  •  19-10-2022
  •  | 
  •  

Question

Trying to access RichTextBox methods when C# recognizes it as a control!

I'm trying to access RichTextBox class methods when the RichTextBox is recognized as a member of the Control class. I've currently tried:

private void new_Page()
{
    TabControl tbcPages = TabControl();
    TabPage first = new TabPage();
    RichTextBox rtb = new RichTextBox();
    rtb.Text = "Why C#? WHY?!";
    first.Add(rtb);
    tbcPages.Add(first);
}
private void TextSelectionAtSomePoint()
{
    int selectionStart = 0;
    int selectionEnd = 6;
    tbcPages.Controls[0].Controls[0].Select(selectionStart,selectionEnd);
    //This line above does not work as the Select method for the Control class is completely different.
}

But I've also tried this (same new_Page method).

private void TextSelectionAtSomePoint()
{
    int selectionStart = 0;
    int selectionEnd = 6;
    RichTextBox newrtb = (RichTextBox)tbcPages.Controls[0].Controls[0];
    newrtb.Select(selectionStart,selectionEnd);
    tbcPages.Controls[0].Controls.RemoveAt(0);
    tbcPages.Controls[0].Controls.Add(newrtb);
}
Was it helpful?

Solution

private void TextSelectionAtSomePoint() {
    int selectionStart = 0;
    int selectionEnd = 6;
    var temp = tbcPages.Controls[0].Controls[0] as RichTextBox;
    if(temp != null)
        temp.Select(selectionStart,selectionEnd);
}

UPDATE:

As @JonSkeet said in comments, seems the OP expects a RichTextBox here; so if it's not, it really should throw an InvalidCastException, not just ignore it. So, I update the answer to this:

private void TextSelectionAtSomePoint() {
    int selectionStart = 0;
    int selectionEnd = 6;
    ((RichTextBox)tbcPages.Controls[0].Controls[0])
        .Select(selectionStart,selectionEnd);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top