简体   繁体   English

在后面的代码中访问动态生成的表行

[英]Accessing Dynamically generated table row in code behind

I have table in with headings in aspx page. 我在aspx页面中有带标题的表格。 I have add the rows to table dynamically using javascript. 我已经使用JavaScript将行动态添加到表中。 I need to access the newly added table rows in server side. 我需要访问服务器端新添加的表行。 I only able to access heading row, it alwasys show table have only one rows, not able to access newly added rows. 我只能访问标题行,它alwasys show table仅具有一行,而不能访问新添加的行。

ASPX page ASPX页面

<table runat="server" id="tblNew" clientidmode="Static">
                                        <tr>
                                            <th>
                                                Column1
                                            </th>
                                            <th>
                                                Column2
                                            </th>
                                        </tr>
                                    </table>

Javascript function for adding rows. 用于添加行的Javascript函数。

    var table = document.getElementById("SelectedItems");
    var newrow = table.insertRow(0);
    var newcel0 = newrow.insertCell(0);
    var newcel1 = newrow.insertCell(1);

CS TO access table rows CS TO访问表行

    int rowCount=tblNew.Rows.Count;

I always got count value as one. 我总是把计数值当作一。 Help appreciated. 帮助表示赞赏。

Your JavaScript is being executed in your browser. 您的JavaScript正在浏览器中执行。 Your CS code is being executed in your server. 您的CS代码正在服务器中执行。 Your server code is being executed BEFORE the resulting html page is transfered to your webbrowser. 在将结果html页面传输到Web浏览器之前,将执行服务器代码。

Add rows into the table in CS code instead of JavaScript code. 使用CS代码(而不是JavaScript代码)将行添加到表中。 This will solve the problem. 这样可以解决问题。

I would suggest to use hidden field to manage count : 我建议使用隐藏字段来管理计数:

<input type="hidden" value="0" runat="server" id="hiddenRowCount"/>

Now whenever you add new row to the table using javascript, increment the counter as given below : 现在,每当您使用javascript将新行添加到表中时,都按如下所示增加计数器:

var table = document.getElementById("<%=tblNew.ClientID%>");
var newrow = table.insertRow(0);
newrow.insertCell(0);
newrow.insertCell(1);

// get current value of the hidden field
var rowCount = document.getElementById('<%=hiddenRowCount.ClientID%>').value;

if (rowCount != '') {
    rowCount = parseInt(rowCount) + 1;
} else {
    rowCount = 1;
}

document.getElementById('<%=hiddenRowCount.ClientID%>').value = rowCount;

Now you can get total number of rows at code behind asa mentioned below : 现在,您可以在下面提到的asa后面的代码中获取总行数:

int totalRows = this.tblNew.Rows.Count + Convert.ToInt32(this.hiddenRowCount.Value);

Note: If you have to dynamically remove raw using javascript then you have to manage counter for that as well. 注意:如果必须使用javascript动态删除原始文件,则还必须管理该计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM