开发者

How do I access an object created in one event in another event?

I created an object in on event, now I want another event to access it. How do I do this?

I'm doing this in Visual Studio 2010.

I have a form that has three button events. The first button creates an object. I want the second button to use the object. How do I do this?

   public void buttonCreate_Click(object sender, EventArgs e)
    {
        int size;
        int sizeI;
        string inValue;

        inValue = textBoxSize.Text;
        size = int.Parse(inValue);
        inValue = comboBoxSizeI.Text;
        sizeI = int.Parse(inValue);

        Histrograph one = new Histrog开发者_如何学Craph(size, sizeI);
    }

    public void buttonAddValue_Click(object sender, EventArgs e)
    {
        int dataV = 0;
        string inValue;
        inValue = textBoxDataV.Text;
        dataV = int.Parse(inValue);
        one.AddData(dataV); //using the object
    }


If I parse your question correctly, you want to use the one variable created in buttonCreate_Click in buttonAddValue_Click.

To accomplish this you need to make one a class variable, as in:

 class MyForm : Form
 {
    Histogram one;

public void buttonCreate_Click(object sender, EventArgs e)
{
    int size;
    int sizeI;
    string inValue;

    inValue = textBoxSize.Text;
    size = int.Parse(inValue);
    inValue = comboBoxSizeI.Text;
    sizeI = int.Parse(inValue);

    one = new Histrograph(size, sizeI);  // NOTE THE CHANGE FROM YOUR CODE
}

public void buttonAddValue_Click(object sender, EventArgs e)
{
    int dataV = 0;
    string inValue;
    inValue = textBoxDataV.Text;
    dataV = int.Parse(inValue);
    one.AddData(dataV); //using the object
}


You can accomplish this by using a private variable as opposed to a local variable

//Declare a private variable
private object _myObject

public void Event1Handler(object sender, EventArgs e)
{
     //Create the object
     _myObject = CreateTheObject();
}


public void Event2Handler(object sender, EventArgs e)
{
    //Use the object
    UseTheObject(_myObject);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜