C# how to object created in Btn_click event access by another Btn_Click
I am using the VS2010 C# language.
I have a form with ENTER button which create an object of class ORDER in Enter_Click(..) event. Now I have another button ADD ITEM which suppose to add a new item in an order when it is clicked.
I t开发者_如何学编程ried to access an Order object created in ENTER button click event, in ADDITEM_Click(..) event, I got the following error:
"Object does not exist in current context"
Any help will be greatly appreciated.
Declare the Order
object in scope of Class
which contain Enter Button Event Handler
and Add Button Event Handler
For example
partial class MyFormClass
{
Order myOrder;
EnterButton_Click(....)
{
myOrder = new Order();
}
AddButton_Click(....)
{
myOrder.Add(....);
}
}
The scope of your Order is limited to the Enter_Click()
event because that is where you declare it. Add the line Order myOrder
at the class level and it will work because the object will continue to exist after the Enter_Click()
method finishes.
精彩评论