Click to See Complete Forum and Search --> : Accessing Components in a Class


bixel
February 14th, 2009, 08:07 PM
C# 2008 Forms

I got a bunch of components in the Form.cs > Form.Designer.cs like Labels and such that I want to manipulate from a different class.

how do I access them?

label1.Text....

BigEd781
February 14th, 2009, 09:39 PM
You should expose properties that allow external classes to modify UI appearance and not give them direct access to the controls.


class ChildForm : Form
{
public string LabelText
{
get { return myLabel.Text; }
set { myLabel.Text = value; }
}
}

bixel
February 15th, 2009, 04:34 PM
That's nifty, and I have forgotten that I see those all the time. Only problem is I get an Object ref required for non-static field in my ClassBox class when using StrText.

If I go back to my Form class and make

public string StrText

this

public static string StrText

I get Object ref required for non-static field in my form class. Dammed if you do dammed if you don't situation.

BigEd781
February 15th, 2009, 04:56 PM
I think that you are trying to do this:

ClassBox.LabelText = "some text";

That would be calling a static method of the ClassBox class. When you made the property static you got another error because the label is not static. You need to do this when you show the dialog:


ClassBox cb = new ClassBox();
cb.LabelText = "Some text";


BTW, the Form class implements IDisposabl, so you should call the Dispose() method after you are done with it. An easy way to do this is by using the "using" keyword:


using (ClassBox cb = new ClassBox)
{
cb.LabelText = "some text";
}


That is really just syntactic sugar. It compiles to this:


try
{
ClassBox cb = new ClassBox();
cb.LabelText = "some text";
}
finally
{
cb.Dispose();
}

bixel
February 15th, 2009, 05:24 PM
hrmm... seems weird. And it looks circular. And after testing..it is. It creates an infinite loop.

namespace Form1
{
public partial class Form1: Form
{

public string StrText
{
get { return lbl_STRrate1.Text; }
set { lbl_STRrate1.Text = value; }
}


and then


class ClassBox : ComboBox
{
Form1.Form1 formtext = new Form1.Form1();

void SetCommonerStats()
{
int iStrength = 10 + Strength;
string sStrength = Convert.ToString(iStrength);
formtext.StrText = sStrength;
}


so instead, I am going to save a new variable in ClassBox and pass it to Form1 and have a function in Form1 that updates it stats. I think this might solve the circular problem.

bixel
February 15th, 2009, 05:37 PM
I just realized I need to completely reorganize the code. I don't need a ClassBox : ComboBox. Instead I need a ClassStatistics Struct. And just have the Form1 access the struct to manipulate a default combobox.

BigEd781
February 15th, 2009, 05:40 PM
There is no reason that you should get an infinite loop. You must be doing something else in another area which is causing it.