1

I am trying to add a new row to HtmlTable on click of button Add Row. It adds one row. But it doesn't add further rows. Please advise.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="eLaundrySearchWeb.Test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
 </head>
<body>
<form id="form1" runat="server">
<div>
<table id="myTable" runat="server">
                            <tr>
                                <td>
                                    <asp:DropDownList ID="DropDownList1"   runat="server">
                                    </asp:DropDownList>
                                </td>
                                <td>
                                    <asp:TextBox ID="txtQty" runat="server">
                                    </asp:TextBox>
                                </td>
                                <td>
                                    <asp:Button ID="Button1" runat="server" Text="Add Row" OnClick="AddRow_Click" 
                                    />
                                </td>
                            </tr>
                        </table>
</div>
</form>

protected void AddRow_Click(object sender, EventArgs e)
    {
        //Random r=new Random();
        //int rv=r.Next(0,100);
        int numOfRows = myTable.Rows.Count;
        HtmlTableRow row = new HtmlTableRow();
        row.ID = "tbl_row"+(numOfRows+1);
        HtmlTableCell cell1 = new HtmlTableCell();
        cell1.ID = "tbl_cell1"+ (numOfRows+1);
        TableCell cell2 = new TableCell();
        cell2.ID = "tbl_cell2" + (numOfRows + 1);
        TextBox tb = new TextBox();
        tb.ID = "tbQty" + (numOfRows + 1);
        cell1.Controls.Add(tb);
        row.Cells.Add(cell1);
        myTable.Rows.Add(row);
        myTable.DataBind();
    }
crazyTechie
  • 2,517
  • 12
  • 32
  • 41

1 Answers1

0

It is adding the rows every time you click the button.The only problem here is that the button is causing the postback and on postback the controls that were dynamically created are getting cleared.Then your button click event adds a row again.So it seems to you that the row is only added once.But in reality it is getting added everytime,it's just that on postback the earlier ones are getting cleared. Trying converting your code into a function and call that function on postback.

Similar SO Question

Community
  • 1
  • 1
Priyank Patel
  • 6,898
  • 11
  • 58
  • 88
  • looks like i need to handle all the rows again. Click for first time => add 1 row. click 2nd time=> add 2 rows..so on – crazyTechie Nov 06 '12 at 15:26
  • @crazyTechie Ya you will need to keep track of the count using Viewstate , you can look at the question I referred to and may be do it accordingly. – Priyank Patel Nov 06 '12 at 15:32