logo

将 GridView 的行列进行转换

作者:孟宪会 阅读:1791 发表于:2010-10-14 13:16:17

本文采取 JavaScript 的方法,还可以采用 DataTable 实现。代码如下:

ASPX 代码
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<script runat="server">
  protected System.Data.DataTable CreateMengxianhuiDataSource()
  {
    System.Data.DataTable dt
= new System.Data.DataTable();
    System.Data.DataRow dr;
    dt.Columns.Add(
new System.Data.DataColumn("id", typeof(System.Int32)));
    dt.Columns.Add(
new System.Data.DataColumn("Name", typeof(System.String)));
    dt.Columns.Add(
new System.Data.DataColumn("Count", typeof(System.Double)));
    dt.Columns.Add(
new System.Data.DataColumn("CreateDate", typeof(System.DateTime)));

    System.Random rd
= new System.Random();
    
for (int i = 0; i < 10; i++)
    {
      dr
= dt.NewRow();
      dr[
0] = i + i;
      dr[
1] = "孟子E章" + i.ToString();
      dr[
2] = System.Math.Ceiling(rd.NextDouble() * 1000);
      dr[
3] = DateTime.Now.AddSeconds(rd.Next(Int32.MaxValue));
      dt.Rows.Add(dr);
    }
    
return dt;
  }

  protected
void Page_Load(object sender, EventArgs e)
  {
    GridView1.DataSource
= CreateMengxianhuiDataSource();
    GridView1.DataBind();
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  
<title></title>
  
<script type="text/javascript">
    window.onload
= function () {
      d
= document.getElementById("<%=GridView1.ClientID %>");
      row
= d.rows.length;
      
if (row == 0) {
        alert(
"表格没有数据,无需进行转换。");
        
return;
      }
      column
= d.rows[0].cells.length;
      html
= new Array(column);
      
for (i = 0; i < column; i++) {
        html[i]
= new Array(row);
      }
      table
= document.createElement("table");
      tbody
= document.createElement("tbody");
      
for (i = 0; i < d.rows.length; i++) {
        
for (j = 0; j < d.rows[i].cells.length; j++) {
          html[j][i]
= d.rows[i].cells[j].innerHTML;
        }
      }

      
for (i = 0; i < html.length; i++) {
        tr
= document.createElement("tr");
        
for (j = 0; j < html[i].length; j++) {
          td
= document.createElement("td");
          td.innerHTML
= html[i][j];
          tr.appendChild(td);
        }
        tbody.appendChild(tr);
      }
      table.appendChild(tbody);
      table.setAttribute(
"cellspacing", "0");
      table.setAttribute(
"border", "1");
      table.setAttribute(
"rules", "all");
      table.setAttribute(
"style","border-collapse:collapse;");
   
  document.getElementById("x").appendChild(table);
    }    
  
</script>
</head>
<body>
  
<form id="form1" runat="server">
  
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
  
<h2>转换后的表格</h2>
  
<div id="x"></div>
  
</form>
</body>
</html>