user1353517
user1353517

Reputation: 300

C# Stuck with using Get Set

After following a tutorial online to make a basic program which uses Get and Set with a class. I'm trying to figure out how I'd set a value from a text box so it's stored in my "stored class", clear the data in the textbox and then "get" the data again to show in the textbox so it proves that my first entered data was properly set if that makes sense.
So my form has 3 buttons, set, clear, get and 1 text box. Here is the code for my 'stored class',

    namespace Pracitse{
class Stored
{        

    private string Colour;
    private string getColour(string colour)
    {
        string displayColour;
        displayColour = colour;
        return displayColour;
    }


    public string MyProperty 
    {
        get { return Colour; }
        set{ Colour = getColour (value) ;}
    }   
    }

And this is the code from my form:

    private void setBtn_Click(object sender, EventArgs e){          
        Stored Details = new Stored();
        string setcolour;
        setcolour = Details.MyProperty;
        Details.MyProperty = colourBx.Text;             

    }

    private void getBtn_Click(object sender, EventArgs e)
    {
        Stored Details = new Stored();             
        string Displaycolour;
        Displaycolour = Details.MyProperty;
        colourBx.Text = (Displaycolour);                     
    }

    private void clrBtn_Click(object sender, EventArgs e)
    {            
        colourBx.Clear();            
    }       
}}

I've used google and tried to follow other tuts but I just can't seem to figure out how to store the first entered data. Any help? thanks.

Upvotes: 0

Views: 391

Answers (2)

Matt Burland
Matt Burland

Reputation: 45155

Your problem is that you are creating (instantiating) a new and completely separate object of type Stored in your click handlers. The MyProperty of your Stored class is an instance property and belongs only to that particular instance of the object.

What you need to do is create a single Stored object in your form as a class member and refer to it in both handlers rather than creating new objects.

In other words, what Oded said two minutes before I hit submit!

Upvotes: 1

Oded
Oded

Reputation: 499382

Every time you do Stored details = new Stored();, you have a new, different Stored object.

You need to have a shared one:

Stored details = new Stored();

private void setBtn_Click(object sender, EventArgs e){          
    details.MyProperty = colourBx.Text;             
}

private void getBtn_Click(object sender, EventArgs e)
{
    string Displaycolour;
    Displaycolour = details.MyProperty;
    colourBx.Text = Displaycolour;
}

private void clrBtn_Click(object sender, EventArgs e)
{            
    colourBx.Clear();            
}    

Upvotes: 8

Related Questions