【问题标题】:add row from asp.net code behind to htmltable将后面的 asp.net 代码行添加到 htmltable
【发布时间】:2012-11-06 07:09:07
【问题描述】:

我正在尝试通过单击“添加行”按钮向 HtmlTable 添加新行。 它增加了一行。但它不会添加更多行。请指教。

<%@ 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();
    }

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    每次单击button 时都会添加行。这里唯一的问题是button 导致postbackpostback 上动态创建的控件被清除。然后你的button点击事件再次添加一行。所以在你看来,该行只添加了一次。但实际上它每次都被添加,只是在postback上更早的那些被清除了。 尝试将您的代码转换为函数并在 postback 上调用该函数。

    Similar SO Question

    【讨论】:

    • 看起来我需要再次处理所有行。第一次单击 => 添加 1 行。点击第二次=>添加2行..等等
    • @crazyTechie 是的,您需要使用 Viewstate 跟踪计数,您可以查看我提到的问题并可能会相应地进行操作。
    猜你喜欢
    • 1970-01-01
    • 2012-01-04
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2011-11-23
    • 2014-01-18
    • 2012-08-25
    相关资源
    最近更新 更多