Reputation: 133
I am using Visual Studio 2010 for C#, I am messing around with some classes and objects before building the application I want to build.
The form I have built has a form1_load event that creates an instance of an object I want to manipulate throughout the form.
When I click a button I want to be able to call one of the methods of my object to execute some statements. I cannot get this to work however, it tells me that the object doesn't exist in the current context, how to I pass this object along to the click event so I can manipulate it?
public void Form1_Load(object sender, EventArgs e)
{
MyPerson bozo = new MyPerson("bozo",48,23);
textBox2.Text = bozo.name;
}
public void button1_Click(object sender, EventArgs e)
{
bozo.myMethod(); // c# is saying that this object doesn't exist in the current context.
}
I understand class structures and objects ok, but I often get stuck on accessing them in different places.
Upvotes: 1
Views: 1274
Reputation: 460340
Your object is a local variable in Form_Load
, so it exists there only. You could make it a field or property in the form. For example:
private MyPerson bozo { get; set; }
public void Form1_Load(object sender, EventArgs e)
{
bozo = new MyPerson("bozo",48,23);
textBox2.Text = bozo.name;
}
public void button1_Click(object sender, EventArgs e)
{
bozo.myMethod(); // now you can access it since it "lives" in the whole form
}
Upvotes: 4