Code Smack
Code Smack

Reputation: 163

accessing object created from custom class

I think the problem I am having is related to my understanding of classes and objects.

The question has two parts.

  1. Why cant I see the object car1 to set a text box = to the value of the car1.name.
  2. How do I access the car1 object from any button or method later in my code.

    protected void Page_Load(object sender, EventArgs e)
    {
        Cars car1 = new Cars();
        car1.Name = "Chevy";
    
    }
    
    protected void Button1_Click(object sender, EventArgs e)
    {
    
       TextBox1.Text = car1.Name.ToString();
    
    }
    

car1.Name.ToString(); is not visible from the button action.

Upvotes: 0

Views: 259

Answers (2)

Jonas Wik
Jonas Wik

Reputation: 222

I would suggest putting Car into a property in the class, and utilizing viewstate.

public Cars Car {
get {
    return (Cars) ViewState["Car"];
}
set {
    ViewState["Car"] = value;
}
}

Upvotes: -1

Oded
Oded

Reputation: 499092

You are declaring the car1 variable within the Page_Load method, making it only visible to that method.

You need to make it into a field - declaring it outside of all methods.

Cars car1;

protected void Page_Load(object sender, EventArgs e)
{
    car1 = new Cars();
    car1.Name = "Chevy";
}

protected void Button1_Click(object sender, EventArgs e)
{
   TextBox1.Text = car1.Name.ToString();
}

When done this way, you need to take care to only call methods on car1 after initializing it (i.e. first line of Page_Load in my example), otherwise you will get a NullReferenceException.

An alternative that can avoid the possible exception is to initialize during declaration, as you have done in your example (only as a field instead of a method variable):

Cars car1 = new Cars();
protected void Page_Load(object sender, EventArgs e)
{
    car1.Name = "Chevy";
}

protected void Button1_Click(object sender, EventArgs e)
{
   TextBox1.Text = car1.Name.ToString();
}

Upvotes: 3

Related Questions