views:

202

answers:

1

Hi

I want to have an ASP.net page where the user can add rows to a grid view (think typing values into a textbox and clicking Add to add to the grid view). Clicking a submit button would then persist all rows to the database.

For a low traffic site, what reasonably easy solution would you recommend to achieve this?

Regards

Peter

A: 

I've done this a few times. The basic premise of my solution is that you load the data into a local collection, and store this in the ViewState of the page.

List<MyObject> lst = new List<MyObject>();

// Populate the list from the database here

// Store this list in the ViewState
ViewState["List"] = lst;

I then have a function which binds this list to the GridView, which I call in the first Page_Load, and any function which modifies this list:

function BindList() {
    List<MyObject> lst = (List<MyObject>) ViewState["List"];
    GridView1.DataSource = lst;
    GridView1.DataBind();
}

To add a new item...

function cmdAdd_Click(object sender, EventArgs e) {
    // Retrieve list from ViewState
    List<MyObject> lst = (List<MyObject>) ViewState["List"];

    // Add the new item
    MyObject newObj = new MyObject();    // Populate this from your form
    lst.Add(newObj);

    // Update the list in the ViewState
    ViewState["List"] = lst;

    // Update the grid to show the new item
    BindList();
}

When you want to persist all of the items to the database, simply retrieve the list from the ViewState.

Richard