WebSurfer's Home

Filter by APML

GridView と thead, tbody, tfoot

by WebSurfer 16. December 2012 20:13

GridView も html にレンダリングされると table, tr, th, td などの要素になりますが、thead, tbody, tfoot 要素はデフォルトではレンダリングされません。今回は GridView で thead, tbody, tfoot 要素を追加する方法を書きます。

GridView は、内部で Table コントロール を利用しているようです。

従って、Table コントロール内の TableRow オブジェクトの TableSection プロパティTableRowSection 列挙体 のTableHeader, TableBody, TableFooter のいずれかに設定してやれば thead, tbody, tfoot 要素が追加されます。

以下のコードのような感じです。

実際に動かして試すことができるよう 実験室 にアップしました。興味のある方は試してみてください。html ソースを見れば thead, tbody, tfoot 要素が追加されているのが分かると思います。

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>

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

<script runat="server">
  // データソース用の DataTable を作成
  protected DataTable CreateDataTable()
  {
    DataTable dt = new DataTable();
    DataRow dr;

    dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
    dt.Columns.Add(new DataColumn("Name", typeof(string)));
    dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
    dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
    dt.Columns.Add(new DataColumn("Amount", typeof(Int32)));
    dt.Columns.Add(new DataColumn("Note", typeof(string)));

    for (int i = 0; i < 10; i++)
    {
      dr = dt.NewRow();
      dr["ID"] = i;
      dr["Name"] = "Name_" + i.ToString();
      dr["Price"] = 123000 * (i + 1);
      dr["Qty"] = (i + 1) * 20;
      dr["Amount"] = 123000 * (i + 1) * (i + 1);
      dr["Note"] = "Note_" + i.ToString();
      dt.Rows.Add(dr);
    }
    return dt;
  }

  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      GridView1.DataSource = CreateDataTable();
      GridView1.DataBind();
    }
  }

  protected void GridView1_RowCreated(
    object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.Header)
    {
      e.Row.TableSection = 
        System.Web.UI.WebControls.TableRowSection.TableHeader;
    }
    else if (e.Row.RowType == DataControlRowType.DataRow)
    {
      e.Row.TableSection = 
        System.Web.UI.WebControls.TableRowSection.TableBody;
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
      e.Row.TableSection = 
        System.Web.UI.WebControls.TableRowSection.TableFooter;
    }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:GridView ID="GridView1" 
      runat="server" 
      OnRowCreated="GridView1_RowCreated" 
      ShowFooter="True" 
      EnableViewState="False">
    </asp:GridView>
  </div>
  </form>
</body>
</html>

Tags: , , ,

ASP.NET

About this blog

2010年5月にこのブログを立ち上げました。主に ASP.NET Web アプリ関係の記事です。ブログ2はそれ以外の日々の出来事などのトピックスになっています。

Calendar

<<  November 2025  >>
MoTuWeThFrSaSu
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

View posts in large calendar