Add rows to a Table in run time , one by one

Last post 07-18-2009 9:56 PM by Heinz Stapff. 16 replies.

Sort Posts:

  • Add rows to a Table in run time , one by one

    06-28-2009, 11:42 PM
    • Member
      409 point Member
    • khparhami
    • Member since 04-09-2009, 5:19 AM
    • Tehran
    • Posts 189

     Hi,

    I would like to add rows to a table at run time by clicking a button. Every time I click the button I need one row to be added to the table. what I did now is by clicking the button on row is created and is filled with the table cells but the problem is each time I can add only one row to the table, when I click to add another the old row will be replaced with the new one , therefore I have one row in the table everytime.

    please advise.

    Best regards
    Khashayar

    ---------------------------------------------
    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 1:31 AM
    • Participant
      1,082 point Participant
    • sagnikmukh
    • Member since 07-29-2008, 6:57 PM
    • Kolkata
    • Posts 214

    try something like,http://sagnikmukh.blogspot.com/2009/03/how-to-add-dynamic-tables-for-each.html

    Sagnik Mukherjee,

    "Only a life lived for others is a life worthwhile."
    --Albert Einstein
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 1:34 AM
    • All-Star
      90,346 point All-Star
    • vinz
    • Member since 10-05-2007, 11:47 AM
    • Cebu, Philippines
    • Posts 13,636
    • TrustedFriends-MVPs

    khparhami:
    I would like to add rows to a table at run time by clicking a button. Every time I click the button I need one row to be added to the table. what I did now is by clicking the button on row is created and is filled with the table cells but the problem is each time I can add only one row to the table, when I click to add another the old row will be replaced with the new one , therefore I have one row in the table everytime.

    You might be interested on this:

    Adding Dynamic Rows in GridView with TextBoxes


    Best Regards,
    Vincent Maverick Durano
    SDE|Microsoft MVP - ASP/ASP.NET

    "Code,Beer and Music ~ my way of being a programmer"
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 2:02 AM
    • Member
      409 point Member
    • khparhami
    • Member since 04-09-2009, 5:19 AM
    • Tehran
    • Posts 189

    Hi,

    No , What I need is to add new rows into an ASP Table not a gridview. any way thanks

    Best regards
    Khashayar

    ---------------------------------------------
    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 2:06 AM
    • All-Star
      23,792 point All-Star
    • PeteNet
    • Member since 01-21-2009, 1:15 PM
    • Posts 3,400

    try this out:

    ASPX:

            <asp:PlaceHolder ID="PlaceHolder1" runat="server">
                <asp:Table ID="Table1" runat="server">
                    <asp:TableRow runat="server">
                        <asp:TableCell runat="server">
                        </asp:TableCell>
                        <asp:TableCell ID="TableCell1" runat="server">
                        </asp:TableCell>
                    </asp:TableRow>
                </asp:Table>
            </asp:PlaceHolder>



    ASPX.CS:

            protected void Button1_Click(object sender, EventArgs e)
            {
                PlaceHolder plholder = (PlaceHolder)Page.FindControl("PlaceHolder1");
                if (plholder != null)
                {
                    Table tb = (Table)plholder.FindControl("Table1");
                    if (tb != null)
                    {
                        TableRow trow = new TableRow();
                        trow.Cells.Add(new TableCell());
                        trow.Cells.Add(new TableCell());
                        tb.Controls.Add(trow);
                    }
                }
            }


    I have not done the ID's or name's etc but if you do a view source you'll see that you have them. you can now add other controls into them.

    Regards,
    Peter
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 2:13 AM
    • Member
      409 point Member
    • khparhami
    • Member since 04-09-2009, 5:19 AM
    • Tehran
    • Posts 189

     No , I'm not talking about database tables , I would like to add rows to an ASP Table.

    thanks

    Best regards
    Khashayar

    ---------------------------------------------
    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 2:23 AM

     Hi,

    see this link

    http://www.java2s.com/Code/ASP/HTML-Control/HTMLTableaddrowVBnet.htm

    <%@ Page Language=VB Debug=true %>
    <script runat=server>
    Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
        Dim MyRow as new HTMLTableRow
        Dim MyCell as new HTMLTableCell
        Dim i as Integer
        Dim j as Integer
        Table1.BGColor="Ivory"
        Table1.Border=2
        Table1.BorderColor="LawnGreen"
        Table1.CellPadding=4
        Table1.CellSpacing=3
        Table1.Align="Center"
        MyCell.InnerText = "Column 1"
        MyRow.Cells.Add(MyCell)
        MyCell = New HTMLTableCell
        MyCell.InnerText = "Column 2"
        MyRow.Cells.Add(MyCell)
        Table1.Rows.Add(MyRow)
        For i = to 6
            MyRow = New HTMLTableRow
            For j = to 2
                MyCell = New HTMLTableCell
                MyCell.InnerText = "Cell " & i & ", " & j
                MyRow.Cells.Add(MyCell)
            Next
            Table1.Rows.Add(MyRow)
        Next    
    End Sub
    </SCRIPT>
    <HTML>
    <HEAD>
    <TITLE>Adding Rows and Cells to an HTMLTable Control through Code</TITLE>
    </HEAD>
    <BODY>
    <form runat="server">
    <Table
        id="Table1"
        runat=server
    >
    </Table>
    </Form>
    </BODY>
    </HTML>

    thanks :)

     

    Remember to click “Mark as Answer” on the post, if it helps you. Because It helps others to find the solution.

    Srinivas Kotra.


  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 2:24 AM

    THEAD { FONT-WEIGHT: bold; BACKGROUND-COLOR: lightyellow } TFOOT { FONT-WEIGHT: bold; BACKGROUND-COLOR: lightgreen } #myTABLE { BACKGROUND-COLOR: bisque } var theTable, theTableBody; function init() { theTable = (document.all) ? document.all.myTABLE : document.getElementById("myTABLE") theTableBody = theTable.tBodies[0] } function appendRow(form) { insertTableRow(form, -1) } function addRow(form) { insertTableRow(form, form.insertIndex.value) } function insertTableRow(form, where) { var now = new Date() var nowData = [now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds()] clearBGColors() var newCell var newRow = theTableBody.insertRow(where) for (var i = 0; i

    try below example, copy paste below code into a .html and open

     <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML><HEAD><TITLE>Modifying Table Cell Content</TITLE>
    <META http-equiv=Content-Type content="text/html; charset=windows-1252">
    <STYLE type=text/css>THEAD {
    FONT-WEIGHT: bold; BACKGROUND-COLOR: lightyellow
    }
    TFOOT {
    FONT-WEIGHT: bold; BACKGROUND-COLOR: lightgreen
    }
    #myTABLE {
    BACKGROUND-COLOR: bisque
    }
    </STYLE>

    <SCRIPT language=JavaScript>
    var theTable, theTableBody;
    function init()
    {
    theTable = (document.all) ? document.all.myTABLE : document.getElementById("myTABLE")
    theTableBody = theTable.tBodies[0]
    }
    function appendRow(form)
    {
    insertTableRow(form, -1)
    }
    function addRow(form)
    {
    insertTableRow(form, form.insertIndex.value)
    }
    function insertTableRow(form, where)
    {
    var now = new Date()
    var nowData = [now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds()]
    clearBGColors()
    var newCell
    var newRow = theTableBody.insertRow(where)
    for (var i = 0; i < nowData.length; i++)
    {
    newCell = newRow.insertCell(i)
    newCell.innerHTML = nowData[i]
    newCell.style.backgroundColor = "salmon"
    }
    updateRowCounters(form)
    }
    function removeRow(form)
    {
    theTableBody.deleteRow(form.deleteIndex.value)
    updateRowCounters(form)
    }
    function insertTHEAD(form)
    {
    var THEADData = ["Hours","Minutes","Seconds","Milliseconds"]
    var newCell
    var newTHEAD = theTable.createTHead()
    newTHEAD.id = "myTHEAD"
    var newRow = newTHEAD.insertRow(-1)
    for (var i = 0; i < THEADData.length; i++)
    {
    newCell = newRow.insertCell(i)
    newCell.innerHTML = THEADData[i]
    }
    updateRowCounters(form)
    form.addTHEAD.disabled = true
    form.deleteTHEAD.disabled = false
    }
    function removeTHEAD(form)
    {
    theTable.deleteTHead()
    updateRowCounters(form)
    form.addTHEAD.disabled = false
    form.deleteTHEAD.disabled = true
    }
    function insertTFOOT(form)
    {
    var TFOOTData = ["Hours","Minutes","Seconds","Milliseconds"]
    var newCell
    var newTFOOT = theTable.createTFoot()
    newTFOOT.id = "myTFOOT"
    var newRow = newTFOOT.insertRow(-1)
    for (var i = 0; i < TFOOTData.length; i++)
    {
    newCell = newRow.insertCell(i)
    newCell.innerHTML = TFOOTData[i]
    }
    updateRowCounters(form)
    form.addTFOOT.disabled = true
    form.deleteTFOOT.disabled = false
    }
    function removeTFOOT(form)
    {
    theTable.deleteTFoot()
    updateRowCounters(form)
    form.addTFOOT.disabled = false
    form.deleteTFOOT.disabled = true
    }
    function insertCaption(form)
    {
    var captionData = form.captionText.value
    var newCaption = theTable.createCaption()
    newCaption.innerHTML = captionData
    form.addCaption.disabled = true
    form.deleteCaption.disabled = false
    }
    function removeCaption(form)
    {
    theTable.deleteCaption()
    form.addCaption.disabled = false
    form.deleteCaption.disabled = true
    }
    // housekeeping functions
    function updateRowCounters(form)
    {
    var sel1 = form.insertIndex
    var sel2 = form.deleteIndex
    sel1.options.length = 0
    sel2.options.length = 0
    for (var i = 0; i < theTableBody.rows.length; i++)
    {
    sel1.options[i] = new Option(i, i)
    sel2.options[i] = new Option(i, i)
    }
    form.removeRowBtn.disabled = (i==0)
    }
    function clearBGColors()
    {
    for (var i = 0; i < theTableBody.rows.length; i++)
    {
    for (var j = 0; j < theTableBody.rows[i].cells.length; j++)
    {
    theTableBody.rows[i].cells[j].style.backgroundColor = ""
    }
    }
    }
    </SCRIPT>

    <META content="MSHTML 6.00.6000.16735" name=GENERATOR></HEAD>
    <BODY onload=init()>
    <H1>Modifying Tables</H1>
    <HR>

    <FORM name=controls>
    <FIELDSET><LEGEND>Add/Remove Rows</LEGEND>
    <TABLE cellSpacing=20 width="100%">
      <TBODY>
      <TR>
        <TD><INPUT onclick=appendRow(this.form) type=button value="Append 1 Row"></TD>
        <TD><INPUT onclick=addRow(this.form) type=button value="Insert 1 Row"> at
          index: <SELECT name=insertIndex> <OPTION value=0
          selected>0</OPTION></SELECT></TD>
        <TD><INPUT disabled onclick=removeRow(this.form) type=button value="Delete 1 Row" name=removeRowBtn>
          at index: <SELECT name=deleteIndex> <OPTION value=0
          selected>0</OPTION></SELECT></TD></TR></TBODY></TABLE></FIELDSET>
    <FIELDSET><LEGEND>Add/Remove THEAD and TFOOT</LEGEND>
    <TABLE cellSpacing=20 width="100%">
      <TBODY>
      <TR>
        <TD><INPUT onclick=insertTHEAD(this.form) type=button value="Insert THEAD" name=addTHEAD><BR><INPUT disabled onclick=removeTHEAD(this.form) type=button value="Remove THEAD" name=deleteTHEAD>
        </TD>
        <TD><INPUT onclick=insertTFOOT(this.form) type=button value="Insert TFOOT" name=addTFOOT><BR><INPUT disabled onclick=removeTFOOT(this.form) type=button value="Remove TFOOT" name=deleteTFOOT>
        </TD></TR></TBODY></TABLE></FIELDSET>
    <FIELDSET><LEGEND>Add/Remove Caption</LEGEND>
    <TABLE cellSpacing=20 width="100%">
      <TBODY>
      <TR>
        <TD><INPUT onclick=insertCaption(this.form) type=button value="Add Caption" name=addCaption></TD>
        <TD>Text: <INPUT size=40 value="Sample Caption" name=captionText>
        <TD><INPUT disabled onclick=removeCaption(this.form) type=button value="Delete Caption" name=deleteCaption></TD></TR></TBODY></TABLE></FIELDSET>
    </FORM>
    <HR>

    <TABLE id=myTABLE cellPadding=10 border=1>
      <TBODY></TBODY></TABLE></BODY></HTML>


    Mark as Answer
    on the posts replys that helped you.
    My Blog -: MSChart

  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 2:24 AM
    • Member
      409 point Member
    • khparhami
    • Member since 04-09-2009, 5:19 AM
    • Tehran
    • Posts 189

     Hi,

    thanks for the code but it inserts only one row and the next click on th button will not add a new row but  over writes the last row.

    I know that it is related to loading and the stateview but I dont know where to put the code in order to save my table rows after each postback.

    thans again

    Best regards
    Khashayar

    ---------------------------------------------
    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 2:40 AM
    • Member
      409 point Member
    • khparhami
    • Member since 04-09-2009, 5:19 AM
    • Tehran
    • Posts 189

     Hi , I need to use the .NET only , no javascripts

    Best regards
    Khashayar

    ---------------------------------------------
    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 2:44 AM
    Answer
    • All-Star
      90,346 point All-Star
    • vinz
    • Member since 10-05-2007, 11:47 AM
    • Cebu, Philippines
    • Posts 13,636
    • TrustedFriends-MVPs

    Here's a working example for your reference:

    using System;
    using System.Configuration;
    using System.Data;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Collections.Generic;
    using System.Collections;
    
    
    public partial class _Default1 : System.Web.UI.Page 
    {
        private int numOfRows = 1;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GenerateTable(numOfRows);
            }
        }
    
    
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (ViewState["RowsCount"] != null)
            {
                numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
                GenerateTable(numOfRows);
            }
        }
    
        private void GenerateTable(int rowsCount)
        {
    
            //Creat the Table and Add it to the Page
            Table table = new Table();
            table.ID = "Table1";
            Page.Form.Controls.Add(table);
    
            const int colsCount = 3;
    
            // Now iterate through the table and add your controls
    
            for (int i = 0; i < rowsCount; i++)
            {
                TableRow row = new TableRow();
                for (int j = 0; j < colsCount; j++)
                {
                    TableCell cell = new TableCell();
                    TextBox tb = new TextBox();
    
                    // Set a unique ID for each TextBox added
                    tb.ID = "TextBoxRow_" + i + "Col_" + j;
                    // Add the control to the TableCell
                    cell.Controls.Add(tb);
                    // Add the TableCell to the TableRow
                    row.Cells.Add(cell);
                }
    
                // And finally, add the TableRow to the Table
                table.Rows.Add(row);
            }
    
            //Sore the current Rows Count in ViewState
            rowsCount++;
            ViewState["RowsCount"] = rowsCount;
        }
    }
    


    Best Regards,
    Vincent Maverick Durano
    SDE|Microsoft MVP - ASP/ASP.NET

    "Code,Beer and Music ~ my way of being a programmer"
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 3:28 AM
    • Member
      106 point Member
    • sangeetonly
    • Member since 05-29-2009, 12:57 PM
    • NOIDA
    • Posts 24

    DataTable dtdt=new DataTable()

       protected void Page_Load(object sender, EventArgs e)
        {

             if (!IsPostBack)
             {
                //Set Count to 0
                Session["clk"]=0;
             }
         }

     protected void btnAdd_Click(object sender, EventArgs e)
     {
             if (Convert.ToInt32(Session["clk"]) == 0)
                {

    ///Add A Row to dt  
                   dt.Rows.Add(dt.NewRow())
                 }
    else
    {   //Add Rows Equal To Number of click that saved in session["clk"]

             for (int i = 0; i <= Convert.ToInt32(Session["clk"]); i++)
                   {
                     dt.Rows.Add(dt.NewRow())
                   }

    }  
    }

    protected void btnreset_Click(object sender, EventArgs e)
     {

    Session["clk"]="0";

    dt.reset();

    }

     

    Sangeet

    Happy Coding


    Please: Don't forget to click "Mark as Answer" on the post that helped you.

    That way future readers will know which post solved your issue.

     

    Sangeet

    ("I would love to change the world, but they won’t give me the source code")





    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 3:50 AM
    • Member
      409 point Member
    • khparhami
    • Member since 04-09-2009, 5:19 AM
    • Tehran
    • Posts 189

     Thanks , I think this is almost what I was asking for , now every time I click the button , a new row is added . the problem is , I need to put different values in the cells of each row ( imagine that I am making an invoice with different lines of items) each time the user should be able to add new item with new quantity. bu with this code the last entered row will be repeated to all rows.

    do you have any solution in your mind?

    thanks again for your time

    Best regards
    Khashayar

    ---------------------------------------------
    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Add rows to a Table in run time , one by one

    06-29-2009, 5:08 AM
    • Member
      409 point Member
    • khparhami
    • Member since 04-09-2009, 5:19 AM
    • Tehran
    • Posts 189

     Dear vinz,

    Thanks , I think this is almost what I was asking for , now every time I click the button , a new row is added . the problem is , I need to put different values in the cells of each row ( imagine that I am making an invoice with different lines of items) each time the user should be able to add new item with new quantity. bu with this code the last entered row will be repeated to all rows.

    do you have any solution in your mind?

    thanks again for your time

    Best regards
    Khashayar

    ---------------------------------------------
    Please: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue.
  • Re: Add rows to a Table in run time , one by one

    07-02-2009, 1:09 AM
    Answer

    Hi,

    Here we may need to know before we continue solving the issue that why the additional row can be added at the first time, but falls to be added later.

    When framework rendering the page, it just displays what we wrote in HTML source and what we hoped to be changed by the behind-code. That means, when the first time we want to add the row, framework render the original table first and then, add a row according to our code. But the next time we hope to add another new row, framework has no idea about the previous row we had already created. It just, like what it always does, displays the HTML source, where the original table with the original row count is, and then, add one row according to the code.

    That is the reason why we cannot add the second, third and more new row to the table. Have a read at this FAQ may help you more to understand this issue: FAQ: Why do dynamic controls disappear on postback and not raise events?.

    Then, let's focus on what we need to do. Since we can already create rows by a loop and a ViewState storing the rowunmber, the problem now is how to set the TextBox's value after postback.

    Based on the solution vinz producted, I suggest you following the block below to modify the code around Line 56.

    TextBox tb = new TextBox();
    tb.ID = "TextBoxRow_" + i + "Col_" + j;
    
    //here, please add this if statements to set the value of the TextBox
    if (Request.Form["TextBoxRow_" + i + "Col_" + j] != null)
    {
        tb.Text = Request.Form["TextBoxRow_" + i + "Col_" + j];
    }
    
    cell.Controls.Add(tb);
    row.Cells.Add(cell);

    Best Regards,
    Shengqing Yang

    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread : )
Page 1 of 2 (17 items) 1 2 Next >