How to access the controls in the TabPage of a TabControl

I have two Buttons in my Form and two TextBoxes inside a TabControl.

I'm not sure how I can save to the Clipboard the text of the TextBoxes using the Buttons.
To do this, we tried to assigned the same AccessibleName to the controls.

I worked on the code but I do not know how to access the TabPages of the TabControl.
Finally, does someone know of a better way to do that?

See Screen Shot of my Form

public partial class Form1 : Form
{ private void SaveNumBot(object sender, EventArgs e) { foreach (Control c in this.Controls) { if (c.AccessibleName == ((Control)sender).AccessibleName) { if (c is TextBox) { Clipboard.SetDataObject(c.Text); } } } }
0

2 Answers

Use pattern matching:

if (c is TextBox textBox)
{ Clipboard.SetDataObject(textBox.Text);
}
1

You could modify your foreach loop:

foreach(TabPage tabPage in yourTabControl.Controls)
{ foreach (TextBox textBox in tabPage.Controls.OfType<TextBox>().Where(x=>x.AccessibleName == ((Control)sender).AccessibleName)) { Clipboard.SetDataObject(textBox.Text); }
}

with this loop you only search for Controls which are from the type Textbox. Use OfType method to avoid InvalidCastExceptions. If you have other Controls which inherit from TextBox in your Form I would recommend to add the line x.GetType()==typeof(TextBox) to the Where() method. With the Where() method we only choose the items which have to same AccessibleName like our sender.

But if you have more textboxes with the same AccessibleName, this loop will run through all items and only choose the last text.

In this case i would recommend:

Clipboard.SetDataObject(yourTabPage.Controls.OfType<TextBox>() .Where(x=>x.AccessibleName ==((Control)sender).AccessibleName)) .ToList() .FirstOrDefault().Text);

Here we are going to have 1 text from the first texbox found in the Control. you could also select the Last()entry.

7

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like