Lucas Araujo
Lucas Araujo

Reputation: 143

Object's instance lost when I add an item to the object's List c# asp.net

I have an object which I initialize on a page's code behind

Here's an example of this object's class

public Class Thing
{
    List<OtherThing> _thisList;
    public List<OtherThing> ThisList
    {
        get { return _thisList; }
        set { _thisList= value; }
    }
    public Thing()
    {
        this._thisList=new List<OtherThing>();
    }
}

and here's my page's code behind

public partial class form : System.Web.UI.Page
{
    private Thing theThing = new Thing();

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        OtherThing OT = new OtherThing(txtName.Text, Convert.toInt32(txtId.Text);
        TheThing.ThisList.Add(OT);
        this.gridview.DataSource=null;
        this.gridview.DataSource=TheThing.ThisList();
        this.gridview.DataBind();
    }
}

Yet each time I add an element, the gridview displays only the latest one added, I tried debugging and found that when I press the button a second time "TheThing"'s list's count displays 0

Upvotes: 0

Views: 394

Answers (2)

Shyju
Shyju

Reputation: 218732

Because every time you click the button, it will execute this line

private Thing theThing = new Thing();

Which is initializing a new object of Thing, and in the constructor of that, you are initializing the ThisList property to an empty list.

Put a breakpoint in that line and you can see it

If you want to persist data between multiple calls, you should persist it somewhere and read from there. You can store it in session state,application state, memory cache, a file in disk or a database.

Remember, Http is (and should be) stateless. Ideally every call to your page has no idea what the previous call did. Interestingly, Contradicting to this principle, Webforms uses something called ViewState to persist data of ui controls (dropdown control etc) between calls (post back on a button click). This is more like a hack to bring the stateful nature (like a windows forms application) to web forms!

BTW, your class can simply use Auto properties, as it is not doing anything fancy with the set and get operations

public class Thing
{
    public List<OtherThing> ThisList { get; set; }
    public Thing()
    {
        this.ThisList = new List<OtherThing>();
    }
}

Upvotes: 1

Vijunav Vastivch
Vijunav Vastivch

Reputation: 4191

It is Because:

you Declared this.gridview.DataSource=null; Everytime when button add was clicked.

try to put this in your Form load event:

this.gridview.DataSource=null;

and in your button Click Event:

protected void btnAdd_Click(object sender, EventArgs e)
    {
        OtherThing OT = new OtherThing(txtName.Text, Convert.toInt32(txtId.Text);
        TheThing.ThisList.Add(OT);
        this.gridview.DataSource=TheThing.ThisList();
        this.gridview.DataBind();
    }

Upvotes: 0

Related Questions