How to access an object from an event?

  • Thread starter Thread starter Doru Roman
  • Start date Start date
D

Doru Roman

Hi,

I have a class MyClass and in the Button1_click() event I create an instance
of that class

MyClass myc = new MyClass();

In another event I want to access myc for serialization purposes.
Let's say it is Buton2_click() event .

How do I access myc object as it is invisible in the Button2_click event?

Thanks,
Doru
 
Doru Roman said:
I have a class MyClass and in the Button1_click() event I create an instance
of that class

MyClass myc = new MyClass();

In another event I want to access myc for serialization purposes.
Let's say it is Buton2_click() event .

How do I access myc object as it is invisible in the Button2_click event?

You can't, assuming that you don't store it anywhere. If it's a local
variable, the variable only exists while the method is running.

If it's genuine state for an object, it should be an instance field of
the type of that object (eg a form).
 
Thanks Jon,

Then what is the best approach?
I try to use serialization. If the object is saved I want to
unbox the object under a Form_Load event. If the object
is not saved, then I want to create the instance first under
Button1_click event and under a Button2_click I want to save it's state.
To be more descriptive, I try to simulate a playing card deck and I want to
save the cards before I close the application and the next time I open it
I need to use the same configuration of the shufled cards.
 
Doru Roman said:
Then what is the best approach?
I try to use serialization. If the object is saved I want to
unbox the object under a Form_Load event. If the object
is not saved, then I want to create the instance first under
Button1_click event and under a Button2_click I want to save it's state.
To be more descriptive, I try to simulate a playing card deck and I want to
save the cards before I close the application and the next time I open it
I need to use the same configuration of the shufled cards.

Ah, right. Okay, so you need to save the contents to a file, and then
load them in the load event if they're present.

I suggest you split the task in two - first investigate serialization
(look in MSDN and use Google to find serialization tutorials), get the
serialization side of things working with the class you're interested
in, and then hook it up to the actual UI.
 
OK, I got the solution: the object should be saved through serialization in
the same event where the object was created.
The same object can be retrieved in any other event afterwards.
 

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

Back
Top