K0D3R
K0D3R

Reputation: 148

How Can I Use a Semi-Dynamically Created Control Name?

I'm creating a new tab on a TabControl, and inside of that tab contains a RichTextBox semi-dynamically named by setting the name Variable like so:

chatWindow.Name = name + "ChatArea";

"name" being the name of the chat channel the user has joined.

ex: name = Test, RTB Name would be: TestChatArea.

Is there an easy way to access that control via code, or am I going about this the completely wrong way?

Upvotes: 1

Views: 33

Answers (1)

Steve
Steve

Reputation: 216273

To programmatically retrieve the TabPage where your RichTextBox control is contained you should search all the tabPage inside your TabControl and check if any RichTextBox in that page has the Name that you are searching for

foreach(TabPage tp in yourTablControl.TabPages)
{
     RichTextBox rtb = tp.Controls.OfType<RichTextBox().FirstOrDefault(x => x.Name ==  name + "ChatArea");
     if(rtb != null)
     {
         // rtb is your control, do your stuff in a sub
         // passing the found control and break the loop
         DoYouStuffWithRichTextBox(rtb)
         break;
     }
}

Of course you need to have a way to identify the variable part of this code. Meaning the variable name should have been set before entering this loop with the actual value that you are searching for.

This code will be simpler if we can assume that you have just one RichTextBox for each TabPage. In this case, when dinamically creating the TabPage and its RichTextBox you could set the Name property of the TabPage to your chat area and use that as a way to identify your control

TabPage tp = yourTablControl.TabPages["chatAreaName"];
RichTextBox rtb = tp.Controls.OfType<RichTextBox().FirstOrDefault();
if(rtb != null)
{
   ....

Upvotes: 1

Related Questions