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

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?

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)
{
....

Related

When Iterating Through C# Winform Controls I Cannot Use the Rtb Property on Rich Text Box Controls

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
}
}
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;
}
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;
}

How to access the Items of a User Control

I have a C# Form that prints multiple instances of a User Control. Let's say that the form prints 5 instances of the User Control (Please see the link attached). How can I store/save the data inputted in all User Controls? Thanks
Here is the screenshot of the C# Form:
You'll have to store the User Controls when you instantiate them in a List or something.
You could have a class like this:
class SomeUC : UserControl
{
public SomeUC()
{
}
// A public method.
public string GetData()
{
return textBox1.Text;
}
}
Where textBox1 is the Name of a TextBox in your SomeUC
And then inside your main or something.
// Instantiate a List that will hold your UserControls, this has to be outside all methods
List<SomeUC> list = new List<SomeUC>();
// And now when you want to build your UCs
// Instantiate your UserControl
SomeUC uc1 = new SomeUC();
// Store your UserControl in a List or something (Can't help you with that)
list.Add(uc1);
Add as much as you want.
A List is not the only way you can do that, but since you don't know how many UserControls you're going to build beforehand, it makes since to use a List.
And then you can access them from the list by their index.
SomeUC uc1 = list[0];
string data = uc1.GetData();
This is an example of accessing one control (the TextBox) in your SomeUC. For other classes (such as the ComboBox) the interaction is different. Meaning you won't have a Text property in the ComboBox. You'll have to figure out things like that on youself. A little research is what it takes. You can always come back if you couldn't find a solution for something.
You can create a property like this for each item in user control.
public string DG
{
get
{
return txtDG.Text;
}
set
{
txtDG.Text = value;
}
}
Then you can access the control value by using following line in your form.
supposed you have created a usercontrol MyControl and you have placed some object of this control in FlowLayoutPenal (pnlFLP).
To get value from control
string DG = ((MyControl)pnlFLP.Controls[0]).DG;
To set value in control
((MyControl)pnlFLP.Controls[0]).DG = "1";
Try this code for accessing user control in the page
Dim txtName As TextBox = TryCast(UserControlName.FindControl("txtName"), TextBox)

How to determine the active control within a tabControl

I have a tab control through which the user can right-click within one of several richTextBoxes. The textBoxes use the same contextMenuStrip control, and I need to determine which textBox is the active one within the contextMenuStripCopyPaste_Opening event. I would think that the code to determine this would be
tabControl1.SelectedTab.ActiveControl.Name but the ActiveControl property is not available. this.ActiveControl.Name just gives me the name of the tabControl.
How can I determine which textBox is the active control within the tabControl?
You can use the sender paramter to get the ContextMenuStrip then call the ContextMenuStrip.SourceControl property to get the control that opened the context menu.
In this case you can try the following code.
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
var ctxStrip = sender as ContextMenuStrip;
if (ctxStrip == null)
return;
var rtb = ctxStrip.SourceControl as RichTextBox;
if (rtb == null)
return;
}
This code simply casts the sender object to a ContextMenuStrip if this is null then return. (Although should never be). The next line captures the SourceControl and casts the control to a RichTextBox.
If the source control is not a RichTextBox then the result will be null and we cancel as this shouldn't be null unless you bind the context menu to other controls aswell.
I'm not finding anything that is there by default. I would create a list of the rich text boxes, and then use a LINQ statement as the LINQ Select statement would return only the rich text box that has the focus. Something like this.
List rtbList = new List {RichTextBox1, RichTextBox2, RichTextBox3, RichTextBox4}
var FocusedRTB = rtbList.Select(x => x.Focused == true);
switch (FocusedRTB.Name)
{Execute Code for each RichTextBox
}

Setting Active Control on a form to a toolbar

I wanted to set a toolbar to be the active control of the form, did something like this:
this.ActiveControl = this.Controls.Find("toolStrip2", false);
but it is saying it cann't contvert from Control[] to Cnotrol.
So how can I set that toolbar to be the active control?
The method Find returns array of Control instances whose name matches the string you pass to it. The first control in the array, if there is one, should be the one you are looking for.
You can do it using this code:
Control[] controls = this.Controls.Find("toolStrip2", false);
if (controls.Length > 0)
this.ActiveControl = controls[0];

How to access a dynamically created text box in C# whose name is available in string?

I have a dynamically created (runtime creation) textbox whose name is available as a string.What i want to do is access this textbox like we do as normal textboxes .Can any one tell me how to cast it as textbox or any other solution
If you know the name of the textbox and its parent controls, you can do like this:
TextBox tb = (TextBox )parent.Controls["name"];
In addition to Iordan's answer, if you don't know exactly where on your form the textbox is, then this extension method should help alot. Note, Form's inherit from Control somewhere down the track too, so you can call it from that, or any control on your form.
public static class ExtensionMethods
{
public static Control FindControl(this Control root, string name)
{
foreach (Control c in root.Controls)
{
// Check this control
if (c.Name == name) return c;
// Check this controls subcontrols
Control tmp = c.FindControl(name);
if (tmp != null) return tmp;
}
return null;
}
}
If this still isn't flexible enough for you, then you can iterate over System.Windows.Forms.Application.OpenForms
Since you seem to have control over the creation process, put a reference to it in a dictionary.
TextBox txt = DynamicCreate(name);
map[name] = txt;
this.Controls.Add(txt);
All you have to do is look it up in your dictionary, instead of loop through all the controls on the form.
TextBox txt = map["name"];

Categories

Resources