0

I'm fairly new to C# so this might be pretty simple actually though I have spent a couple hours searching without a solution.

I'm working with windows form and I am trying to access an object from another button-click event. The error I'm getting is "The name 'object' does not exist in the current context" when trying to access object in Button2_Click.

    public void Button1_Click(object sender, EventArgs e)
    {
        // Prefilled with a persons info
        MyClass object = new MyClass();
    }

    public void Button2_Click(object sender, EventArgs e)
    {
        // Access object
        string name = object.Name;
    }

So my question is how do I access an object created in another "Button_Click"?

1
  • 1
    You've defined object in a function scope so it's got garbage collected after the function code is executed. You might want to define it in class scope instead. More information here Commented Feb 14, 2018 at 17:47

2 Answers 2

1

A couple of issues exists.

  1. You can't use object as variable name. (object is a reserved keyword)
  2. You can't access a internal variable, within another event.

To solve your issue, you would scope the variable when your initial object is created.

public class Example
{
     // Variable declared as a class global.
     private readonly Sample sample; 

     // Constructor to build our sample.
     public Example() => sample = new Sample(); 

     // Button writing a property from sample.
     protected void btnSend(object sender, EventArgs e) => Console.WriteLine(sample.SomeProperty); 
}

So the object is in the upper portion of your class, when you build Example, a sample is always created. So as you utilize Sample within your Example class, it will be correctly scoped.

I also don't understand why you have to click one button, to populate this object, so I altered to have the object built once Example is created.

Sign up to request clarification or add additional context in comments.

2 Comments

c# 6 syntax might be confusing for someone who is just getting started with c#
@CamiloTerevinto Fair enough, I use the shorthand quite a bit. Second nature to me at this point.
0

The scope of the object should be class level in order to be used by other methods in the same class:

private MyClass _myClassObject; // class level object. Remember "object" is reserved keyword that is why renamed it to "_myClassObject"
public void Button1_Click(object sender, EventArgs e)
{
        // Prefilled with a persons info
        _myClassObject = new MyClass();
}

public void Button2_Click(object sender, EventArgs e)
{
    // Access object
    string name = _myClassObject.Name;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.