NEWBIE Q - accessing a form control from outside of the form class

G

Guest

Hi All,

A simple q for just about anyone to answer i would think. I have a form
called MainForm with a label called label1. I also have a class
TestChange. I want to be able to change label1.Text from the TestChange
class but i dont know how to pass TestChange the reference (if that is
the right word)to MainForm.

(I know the code below is wrong)

thanks

Gary


using System;
using System.Drawing;
using System.Windows.Forms;

namespace test2
{
/// <summary>
/// Description of MainForm.
/// </summary>
public class MainForm : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
public MainForm()
{

InitializeComponent();

TestChange myTestChange = new TestChange(this);
}

[STAThread]
public static void Main(string[] args)
{
Application.Run(new MainForm());
}

#region Windows Forms Designer generated code
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor.
The Forms designer might
/// not be able to load this method if it was changed manually.
/// </summary>
private void InitializeComponent() {
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(80, 160);
this.label1.Name = "label1";
this.label1.TabIndex = 0;
this.label1.Text = "label1";
//
// MainForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.label1);
this.Name = "MainForm";
this.Text = "MainForm";
this.ResumeLayout(false);
}
#endregion
}
public class TestChange
{
public TestChange(Form abc) {
abc.label.Text="changed label";
}
}
}
 
F

Fabio Cannizzo

Your code is not working becuase you set label1 to PRIVATE, hence you cannot
access it from outide the class.
The simplest way is to set label1 to Public. You can do it in the designer
using the property Modifier.
However making variable public is not the recomended way. You should create
a properties or method which does the job.

Fabio
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top