Referencing controls within a class

John 466 Reputation points
2024-07-06T19:17:34.46+00:00

I would like to know how I would reference a control within a class.

This is a code snippet example:

Would need to create a class fille first, or would I create a class within the main project file?

This is to use and instantiate the class again in future builds.

using [Project_Name].Properties;

public class Control_One
{
	Form1 formOne;
	
	
	public void Output_data_to_text_box()
	{
		Form1 formOne = new Form1;
		formOne.[Name_of_Text_Box_control].Text = "Hello there!";
	}

}
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,106 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,909 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,421 Reputation points
    2024-07-07T09:47:53.2933333+00:00

    When dropping a control on a form, by default the control is private to the form. You can select a control, select properties, select the modifier property and set the value to public which allows you to access the control outside of the form. This technique is usually frown on.

    If the control in question is on the form, not in another control like a panel you can use in another form or class.

    if (Application.OpenForms[nameof(Form1)].Controls["textBox1"] is not TextBox textBox) return;
    textBox.Text = "Hello";
    textBox.BackColor = Color.Yellow;
    

    And if the control is in a panel for instance. Add the following class to your project.

    public static class ControlExtensions
    {
        public static IEnumerable<T> Descendants<T>(this Control control) where T : class
        {
            foreach (Control child in control.Controls)
            {
                if (child is T thisControl)
                {
                    yield return (T)thisControl;
                }
    
                if (child.HasChildren)
                {
                    foreach (T descendant in Descendants<T>(child))
                    {
                        yield return descendant;
                    }
                }
            }
        }
    }
    

    Usage from a class or other form.

    var tb = ((Form1)Application.OpenForms[nameof(Form1)])
        .Descendants<TextBox>()
        .FirstOrDefault(x => x.Name == "textBox1"); ;
    if (tb is null) return;
    tb.Text = "Hello";
    tb.BackColor = Color.Yellow;
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.