views:

66

answers:

1

I have a collection of objects I bind to a Listview like this:

   if (!IsPostBack)
        {
            List<Equipment> persons = new List<Equipment>
                             {new Equipment{ItemName = "Sworn", ItemCount = 7, ItemCost = 255},
                              new Equipment{ItemName = "Civ", ItemCount = 3, ItemCost = 80},
                              new Equipment{ItemName = "Civ", ItemCount = 5, ItemCost = 200}};

            lvMain.DataSource = persons;

            BindList();
        }

I want to Add/update/delete from this object collection and submit the final data object collection to the BL when the user saves... Rather than just delete/add/update everytime a row is changed.

So my question is how do I maintain state for that datasource? I have tried this (delete example)

  protected void lvMain_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "Delete":
                {
                    ListViewDataItem lvdi = (ListViewDataItem)e.Item;
                    lvMain.Items.Remove(lvdi);                
                    break;
                }

But it does nothing. I can't rebind it to the datasrouce because at this point the datasource is null.. I assume the listview keeps its own view state which contains the data?... I guess worse case I can always hold the Object Collection in a Session object.. ..

Am I doing something wrong or thinking the wrong way?

A: 

My suggestion would be to store persons in the Viewstate, then add/edit/remove from this.

Store in Viewstate

ViewState["Persons"] = persons;

Get back out of Viewstate

List<Equipment> persons = (List<Equipment>)ViewState["Persons"];

... Perform add/edit/remove on object then store back in the Viewstate

Germ
Ok.. That sounds good..So the collection of data isnt stored in the ListView automatically ?
punkouter
They are, so you could add/edit/remove items from the ListView as long as you don't rebind the ListView. Assuming the ListView has viewstate enabled. (EnableViewState)
Germ