Click here to Skip to main content
15,072,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why does this not work? I have several programs where I need to create an instance from one button and read from the instance when pressing another button. But I can't access the methods and properties. I realize this is a stupid rookie question, but I really want to know to do that :)

Thanks a lot

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace objektLaes
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Objekt nytObjekt = new Objekt(); // declare Objekt
            nytObjekt.sætNavn(textBox1.Text);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox2.Text = nytObjekt.hentNavn; // Can't access Objekt from here. Why not?
        }
    }
}


What I have tried:

The above code sample shows what I intended to do/how I intended to do it
Posted
Updated 27-Oct-17 22:01pm

1 solution

Look at your code:
private void button1_Click(object sender, EventArgs e)
{
    Objekt nytObjekt = new Objekt(); // declare Objekt
    nytObjekt.sætNavn(textBox1.Text);

}
nytObjekt is declared as local to the button1_Click method, and is destroyed when the method ends.
We call this "going out of scope" - when a variable is declared, it is only ever available within the curly brackets around the code it is declared in: so inside a method it is only available within that method and so on.

If you want it available to other methods, it needs to be declared within the class, not the method:

private Objekt nytObjekt = new Objekt();
private void button1_Click(object sender, EventArgs e)
{
    nytObjekt.sætNavn(textBox1.Text);
}

private void button2_Click(object sender, EventArgs e)
{
    textBox2.Text = nytObjekt.hentNavn;
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900