AlwaysANovice
AlwaysANovice

Reputation: 993

How to save data to a (csv/txt) file from dynamically added rows to a HTML table using C#?

I have a table called "newDataTable" where I am adding new rows dynamically with the help of following JavaScript:

    function addRow() 
    {
        //add a row to the rows collection and get a reference to the newly added row
        var table = document.getElementById('newDataTable');
        var lastRow = table.rows.length;
        var newRow = table.insertRow(lastRow);

        //add 6 cells (<td>) to the new row and set the innerHTML to contain text boxes

        var newCell = newRow.insertCell(0);
        newCell.innerHTML = "<label> City: </label>";

        newCell = newRow.insertCell(1);
        newCell.innerHTML = "<input type='text' name='tb_city'/>";

        newCell = newRow.insertCell(2);
        newCell.innerHTML = "<label> State: </label>";

        newCell = newRow.insertCell(3);
        newCell.innerHTML = "<input type='text' name='tb_state'/>";

        newCell = newRow.insertCell(4);
        newCell.innerHTML = "<input title='Add Row' name='addButton' type='button' value='Add' onclick='addRow()' />";

        newCell = newRow.insertCell(5);
        newCell.innerHTML = "<input title='Remove Row' name='deleteButton' type='button' value='Delete' onclick='removeRow(this)' />";
    }

So after everything this is how my page looks like: Screen Snippet of Form

Now, how can I collect the data from the textboxes and save them in a csv/txt file when the user clicks the "Submit" button (using C#)?
One obvious problem I am already seeing is that the way I am adding the rows to the HTML table will not allow me to have ID for each textbox. Is there any way working around this?

I will really appreciate any help that will allow me to save the data w/o changing the addRow() Thank you!!

Upvotes: 4

Views: 2027

Answers (1)

mravey
mravey

Reputation: 4510

Maybe you could try something like :

newCell.innerHTML = "<input type='text' name='tb_city[]'/>";
newCell.innerHTML = "<input type='text' name='tb_state[]'/>";

Here I just changed the name attribute of your inputs by adding [], it will post all you data in an array. So in the server side you just have to iterate through the array to get all you data.

Upvotes: 3

Related Questions