Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple new rows in asp.net Repeater

I'm developing an asp.net page that allows users to enter / edit multiple records. I am using a Repeater control to display the entry fields for each record. I would like to have an "Add" button that when clicked, inserts a new, blank set of entry fields. The user should be able to enter the new record, then click the add button multiple times and continue adding new records. Then, when the user clicks the Save button, those new records will be saved along with the changes to the existing records. If the user does not click Save, the records should be discarded and not written to the database.

Is there any way to implement this "add" functionality with the Repeater control?

like image 925
DCNYAM Avatar asked Nov 13 '22 02:11

DCNYAM


1 Answers

There is a rather simple solution for this. Assuming you have some form of View Model that temporarily holds the data for the whatever the user is entering, you can simply add an additional "blank" ViewModel to the collection that the repeater uses as it's datasource. On save, you could simply save all the modifications to the database that exist in your View Model. A possible example would be:

    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 major caveat here is that you must repopulate the ItemRepeater's datasource with the View Models updated with any changes the user made (that you would wish to keep/show).

like image 60
Jaime Torres Avatar answered Dec 08 '22 01:12

Jaime Torres