How to access a control on a form from another class?
-
C# newbie looking for a simple way to access a control on a form, a label or progress bar, from another class. If not a simple, a difficult one, or even the correct one will suffice. BBB
-
C# newbie looking for a simple way to access a control on a form, a label or progress bar, from another class. If not a simple, a difficult one, or even the correct one will suffice. BBB
It all comes down to references and access. One class must first have a reference to another. So, your form that wants to access a control on another form must have a reference to that form. You could pass a reference as a property, for example. Second, that control has to be accessible. By default, the Windows Forms designer makes all controls you drag-and-drop onto the designer private, so other classes - even derivative classes - can't access the field. You can either change the accecss modifier (you can do this both in the PropertyGrid from the designer or in the code file). You could, however, enumerate the form's
Controls
collection and find the control by name, which would be accessible (just because the control's field is private doesn't mean the control itself is private - only the field that holds the reference to it is). If these are parent/child forms, then you can use theParent
property, for example, of the child form, but you must make sure to cast it to the parent form's type in order to access fields by name. An example follows:using System;
using System.Drawing;
using System.Windows.Forms;
class ParentForm : Form // Default access for class is internal
{
static void Main()
{
Application.Run(new ParentForm());
}
Button openChild; // Default access is private for class members
internal TextBox childText; // Make accessible to child form in this assembly
internal ParentForm()
{
Text = "Example: Parent Form";
openChild = new Button();
Controls.Add(openChild);
openChild.Location = new Point(8, 8);
openChild.Text = "Open Child";
openChild.Click += new EventHandler(openChild_Click);
childText = new TextBox();
Controls.Add(childText);
childText.Location = new Point(8, openChild.Bottom + 8);
childText.ReadOnly = true;
}
void openChild_Click(object sender, EventArgs e)
{
using (ChildForm form = new ChildForm())
form.ShowDialog(this);
}
}
class ChildForm : Form
{
TextBox myText;
internal ChildForm()
{
Text = "Example: Child Form";
myText = new TextBox();
Controls.Add(myText);
myText.Location = new Point(8, 8);
myText.TextChanged += new EventHandler(myText_TextChanged);
}
void myText_TextChanged(object sender, EventArgs e)
{
ParentForm parent = Owner as ParentForm;
if (parent != null)
parent.childText.Text = myText.Text;
}
}You should a