Add some new lines to asp.net Repeater

I am developing an asp.net page that allows users to enter / edit multiple entries. I use the Repeater control to display input fields for each record. I would like the Add button to be pressed, inserts a new empty set of input fields. The user should be able to enter a new entry, then click the add button several times and continue adding new entries. Then, when the user clicks the “Save” button, these new entries will be saved along with changes to existing entries. If the user does not click Save, the records should be discarded and not written to the database.

Is there a way to implement this add function using the Repeater element?

+5
source share
1 answer

There is a fairly simple solution for this. Assuming you have a View Model form that temporarily stores data for what the user enters, you can simply add an additional “empty” ViewModel to the collection that the repeater uses as the data source. When saving, you can simply save all changes to the database that exist in your view model. Possible example:

    protected void btnAdd_OnCommand(object sender, EventArgs e)
    {
        List<Item> items = (List<Item>)this.ItemRepeater.DataSource;
        items.Add(new Item() { Id = -1 });
        this.ItemRepeater.DataBind();
    }

    protected void btnSave_OnCommand(object sender, EventArgs e)
    {
        List<Item> items = (List<Item>)this.ItemRepeater.DataSource;

        foreach (Item itm in items)
        {
            if (itm.Id == -1)
            {
                //Save New Item
            }
            else
            {
                //Update existing item
            }
        }
    }

The main disclaimer here is that you must re-populate the ItemRepeater data source with view models updated with any changes made by the user (which you would like to save / show).

+1

All Articles