I am trying to figure out how to change the properties of controls residing on a form from a separate class. I don't want to make the form controls public (I'm assuming the Windows Form Designer is smarter than I am ;). I created a sample project with a label, two buttons and an external class. (See code below)
One button sends a string to a method in an external class (imaginitively named external_class), which calls an accessor method to change the label. The other button calls the accessor method directly.
The problem is that when the accessor method is called from the external class, it fails silently - it doesn't change the text property of the label. When the accessor method is called via the other button, directly, without going through the external class, it works.
Can anyone explain to me what is going on here?
thanks
Code:
form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace FormAccessTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_change_Click(object sender, EventArgs e)
{
external_class obj = new external_class();
obj.chng_lbl("Change via External class");
}
public void accessor_method(string labeltext)
{
MessageBox.Show("accessor_method call: "+labeltext);
lbl_status.Text = labeltext;
}
private void btn_change2_Click(object sender, EventArgs e)
{
// why does calling accessor_method from here work,
//but not from external_class.chng_lbl ?
accessor_method("Direct Change");
}
private void lbl_status_Click(object sender, EventArgs e)
{
}
}
}
external_class.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace FormAccessTest
{
class external_class
{
Form1 frm_UI;
public external_class()
{
frm_UI = new Form1();
}
public void chng_lbl(string desired_label)
{
frm_UI.accessor_method(desired_label);
}
}
}