有没有办法使用JavaScript将行添加到gridview?现在我将GridView的onclick方法设置为sortTrGrid(gridviewname),sortTrGrid方法的结构如下所示。我可以按照正确的顺序获取表中的行,但网页上没有任何变化。
function sortTrGrid(sender) {
var table = document.getElementById(sender.id);
var rows = new Array(table.rows);
for (var i = 0; i < table.rows; i++) {
rows[i] = table.rows[i];
}
for (var i = table.rows; i > 0; i--) {
table.deleteRow(document.getElementById(i));
table.rows[i] = rows[i];
}
}//end GridSort
答案 0 :(得分:1)
假设您的页面包含数据源中的所有行(无分页),并且您希望在客户端上订购GridView行以提高性能(无需访问服务器),您可以执行以下操作:
(此代码允许在单击GridView标题时对数字和文本进行排序并按升序和降序排序)
如果您想查看完整的工作示例I just uploaded to my GitHub site
<asp:LinqDataSource runat="server" ID="lds"
ContextTypeName="WebForms_1.DataAccess.PubsDataContext"
TableName="jobs"
EntityTypeName="WebForms_1.DataAccess.jobs">
</asp:LinqDataSource>
<asp:GridView runat="server" ID="gv" DataSourceID="lds" DataKeyNames="job_id">
</asp:GridView>
<script type="text/javascript">
$(function () {
var $gv = $("table[id$=gv]");
var $headers = $("th", $gv);
var $rows = $("> tbody > tr:not(:has(table, th))", $gv);
$rows.addClass("grid-rows");
$headers.addClass("grid-headers");
$headers.toggle(function (e) {
sortGrid($(this), 0);
}, function (e) {
sortGrid($(this), 1);
});
function sortGrid(row, direction) {
var colIndex = $(row).parent().children().index($(row));
var $rowsArray = $.makeArray($rows);
var $sortedArray = $rowsArray.sort(function (o, n) {
var $currentCell = $("td:nth-child(" + (colIndex + 1) + ")", $(o));
var $nextCell = $("td:nth-child(" + (colIndex + 1) + ")", $(n));
var currentValue = parseFloat($currentCell.text()) ? parseFloat($currentCell.text()) : $currentCell.text();
var nextValue = parseFloat($nextCell.text()) ? parseFloat($nextCell.text()) : $nextCell.text();
if (direction == 0) {
return currentValue < nextValue ? -1 : 1;
}
else {
return currentValue > nextValue ? -1 : 1;
}
});
$("> tbody > tr:not(:has(table, th))", $gv).remove();
$("tbody", $gv).append($sortedArray);
}
});
</script>