WebSurfer's Home

トップ > Blog 1   |   ログイン
APMLフィルター

DataGrid, GridView に動的に列を追加

by WebSurfer 2013年5月17日 16:41

あまり使い道はないと思いますが、DataGrid と GridView に動的に列を追加する方法を備忘録として書いておきます。 (【2021/9/21 追記】もっと簡単かつスマートにできる方法がありました。詳しくは「DataGrid, GridView に動的に列を追加 (2)」を見てください)

DataGrid に動的に列を追加

DataGrid, GridView ともヘッダ、フッタを含め各行は TableCellCollection で構成されているので、そのコレクションの適切な位置に TableCell を追加することが基本です。

追加したセルの中に文字列や CheckBox などを配置したい場合は、当該セルの ControlCollection に LiteralControl や CheckBox を初期化して追加します。

追加するタイミングは、DataGrid なら ItemCreated イベント、GridView なら RowCreated イベントがよさそうです。

その例を以下のコードに示します。上の画像を表示したものです。実際に動かして試すことができるよう 実験室 にアップしました。興味のある方は試してみてください。

<%@ 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">

  // 表示用のデータソース (DataView) を生成
  ICollection CreateDataSource()
  {
    DataTable dt = new DataTable();
    DataRow dr;
       
    dt.Columns.Add(new DataColumn("Item", typeof(Int32)));
    dt.Columns.Add(new DataColumn("Name", typeof(string)));
    dt.Columns.Add(new DataColumn("Price", typeof(decimal)));

    for (int i = 0; i < 5; i++)
    {
      dr = dt.NewRow();

      dr["Item"] = i;
      dr["Name"] = "Name-" + i.ToString();
      dr["Price"] = 1.23m * (i + 1);

      dt.Rows.Add(dr);
    }

    DataView dv = new DataView(dt);
    return dv;
  }

  // 初回のみデータソースを生成してバインド(ポストバック
  // 時は ViewState から自動的にデータを取得するので不要)
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      ICollection dv = CreateDataSource();
      DataGrid1.DataSource = dv;
      DataGrid1.DataBind();
      GridView1.DataSource = dv;
      GridView1.DataBind();
    }
  }
    
  // GataGrid.ItemCreated イベントで列を動的に追加する。
  // ItemDataBound イベントで行うと以下の問題があるので
  // 注意:
  // (1) ポストバック時にはイベントが発生しないので追加
  //     行を再生できず、結果消えてしまう。
  // (2) 追加コントロールの LoadViewState, LoadPostData 
  //     の呼び出しがうまくいかない。結果、以下の例では 
  //     CheckBox の CheckedChanged イベントの発生が期
  //     待通りにならない。
  protected void DataGrid1_ItemCreated(object sender, 
    DataGridItemEventArgs e)
  {
    if (e.Item.ItemType == ListItemType.Header)
    {
      // ヘッダ行に列(セル)を追加。セルの中にリテ
      // ラルを配置。
      TableCell cell = new TableCell();
      cell.Controls.Add(new LiteralControl("追加列"));
      e.Item.Cells.Add(cell);
    }
    else if (e.Item.ItemType == ListItemType.Item ||
      e.Item.ItemType == ListItemType.AlternatingItem)
    {
      // データ行に列(セル)を追加。セルの中に
      // CheckBox を配置。
      TableCell cell = new TableCell();
      CheckBox cb1 = new CheckBox();
      cb1.AutoPostBack = true;
      cb1.ID = "CheckBoxInItemIndex-" + 
        e.Item.ItemIndex.ToString();
      cb1.CheckedChanged += 
        new EventHandler(cb1_CheckedChanged);
      cell.Controls.Add(cb1);
      e.Item.Cells.Add(cell);
    }
    else if (e.Item.ItemType == ListItemType.Footer)
    {
      // フッタ行に列(セル)を追加。セルの中にリテ
      // ラルを配置。
      TableCell cell = new TableCell();
      cell.Controls.Add(new LiteralControl("追加列"));
      e.Item.Cells.Add(cell);
    }
  }

  protected void cb1_CheckedChanged(object sender, 
    EventArgs e)
  {
    CheckBox cb = (CheckBox)sender;
    Label1.Text = cb.ID + " clicked to " + 
      cb.Checked.ToString();
  }

  // DataGrid の場合と同様な理由で RowDataBound イベ
  // ントではなく RowCreated イベントで動的に列を追
  // 加する。
  protected void GridView1_RowCreated(object sender, 
    GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.Header)
    {
      // ヘッダ行に列(セル)を追加。セルの中にリテ
      // ラルを配置。
      // GridView のヘッダ行は th 要素が使われるので、
      // TableCell でなく TableHeaderCell を用いる。
      TableHeaderCell hc = new TableHeaderCell();
      hc.Controls.Add(new LiteralControl("追加列"));
      e.Row.Cells.Add(hc);
    }
    else if (e.Row.RowType == DataControlRowType.DataRow)
    {
      // データ行に列(セル)を追加。セルの中に
      // CheckBox を配置。
      TableCell cell = new TableCell();
      CheckBox cb2 = new CheckBox();
      cb2.AutoPostBack = true;
      cb2.ID = "CheckBoxInRowIndex-" + 
        e.Row.RowIndex.ToString();
      cb2.CheckedChanged += 
        new EventHandler(cb2_CheckedChanged);
      cell.Controls.Add(cb2);
      e.Row.Cells.Add(cell);
    }
    else if (e.Row.RowType == DataControlRowType.Footer)
    {
      // フッタ行に列(セル)を追加。セルの中にリテ
      // ラルを配置。
      TableCell cell = new TableCell();
      cell.Controls.Add(new LiteralControl("追加列"));
      e.Row.Cells.Add(cell);
    }
  }

  protected void cb2_CheckedChanged(object sender, 
    EventArgs e)
  {
    CheckBox cb = (CheckBox)sender;
    Label2.Text = cb.ID + " clicked to " + 
      cb.Checked.ToString();
  }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>WebSurfer's Page - 実験室</title>
</head>
<body>
  <form id="form1" runat="server">

    <h2>DataGrid</h2>
    <asp:DataGrid ID="DataGrid1"
      runat="server" 
      ShowFooter="True" 
      OnItemCreated="DataGrid1_ItemCreated">
    </asp:DataGrid>
    <asp:Label ID="Label1" runat="server" />

    <h2>GridView</h2>
    <asp:GridView ID="GridView1" 
      runat="server" 
      ShowFooter="True" 
      OnRowCreated="GridView1_RowCreated">
    </asp:GridView>
    <asp:Label ID="Label2" runat="server" />

  </form>
</body>
</html>

Tags: ,

ASP.NET

SqlCommand の Dispose は呼ぶべきか?

by WebSurfer 2013年4月23日 13:58

結論は呼ぶべきなのですが、そのあたりのことについて調べて新発見があったので、備忘録として書いておきます。

SqlConnection クラスの Close メソッド(Dispose と機能的に同じ)を明示的に呼び出して接続を閉じることは、リソースリーク防止のため重要であることはよく知られていると思います。

詳しくは、.NETの例外処理 Part.2 を見てください。特に、そのページに書かれている、"GC の仕組みで防がれるリークはメモリリークである、という点です。実は、アプリケーションにおけるリークには大別してメモリリークとリソースリークがあり、リソースリークは GC のみで防止することができません。" という点に注目です。

では、SqlCommand クラスや SqlDataReader クラスの場合はどうでしょうか? MSDN ライブラリのサンプルコードでも Dispose メソッドを呼び出してないケースが多々見られます。SqlConnection クラスと違ってリソースリークの問題はなさそうですが、メモリリーク防止のため Dispose メソッドを呼び出す必要はないのでしょうか?

MSDN ライブラリの Dispose メソッドの実装 を見ると、"マネージリソースのみを使用する型は、ガベージコレクターによって自動的にクリアされるため、このような型で Dispose メソッドを実装しても、パフォーマンス上の利点はありません。" とのことです。(.NET 4.6 / 4.5 の記事にはその説明はありませんが同じことかと思います)

ということは、アンマネージリソースを使用していない SqlCommand などでは、Dispose メソッドを呼び出してもパフォーマンス上の利点はないということになってしまいます。

しかし、実は、Dispose メソッドには、メモリ開放の機能以外に、GC.SuppressFinalize メソッド を実装することにより、冗長なファイナライザーの呼び出しを防ぐことができるという利点があるそうです。

そのあたりは、MSDN フォーラムの Should I call Dispose on a SQLCommand object? というページで、Microsoft (MSFT) の方が "To prevent a finalizer from running, most well written Dispose implementations call a special method called GC.SuppressFinalize, which indicates to the GC that its finalizer shouldn't be run when it falls out of scope (as the Dispose method did the clean up). The component class (which remember the SqlCommand indirectly inherits from), implements such a Dispose method. Therefore to prevent the finalizer from running (and even though it does nothing in the case of SqlCommand), you should always call Dispose." と述べてられている通りだと思います。

また、Dispose メソッドの実装 の説明にも、"Dispose メソッドは、破棄するオブジェクトの SuppressFinalize メソッドを呼び出す必要があります。 SuppressFinalize を呼び出すと、オブジェクトが終了キューに置かれている場合は、そのオブジェクトの Finalize メソッドの呼び出しは行われません。Finalize メソッドの実行は、パフォーマンスに影響を与えることを覚えておいてください。" と書かれています。(.NET 4.6 / 4.5 の記事にはその説明はありませんが同じことかと思います)

という訳で、結論は、IDisposable インターフェイス を継承して Dispose メソッドを実装しているクラスは、そのオブジェクトが使用されなくなった時点で Dispose メソッドを呼び出すべきということのようです。

そのために良く使われるのが、上に紹介した .NETの例外処理 Part.2 にある try/finally パターンや using ステートメントですね。

using ステートメントを使用すると、以下の例のようになると思います。

using(SqlConnection conn = new SqlConnection("接続文字列"))
{

  conn.Open();

  using(SqlCommand cmd = new SqlCommand("クエリ", conn))
  {
    using (SqlDataReader reader = cmd.ExecuteReader())
    {
      if (reader != null)
      {
        while (reader.Read())
        {
          // 何らかの処置
        }
      }
    } // SqlDataReader の Dispose(注1)

  } // SqlCommand の Dispose

} // SqlConnection の Dispose(注2)

注1:Dispose メソッドは、SqlDataReader によって使用されているリソースを解放し、Close メソッドを呼び出します。

注2:SqlConnection クラスの Close メソッドと Dispose メソッドは、機能的に同じです。

------ 2014/9/25 追記 ------

クラスによってはコンストラクタに GC.SuppressFinalize メソッドが実装されており、冗長な Finalize メソッドの呼び出しを防ぐという意味では Dispose() メソッドを呼ぶ必要はないものもあります。

実は、SqlCommand クラスの場合も、現時点のソースコードを見る限り、コンストラクタに GC.SuppressFinalize メソッドが実装されています。

ただし、コンストラクタでの GC.SuppressFinalize の実装は MSDN ライブラリなどにはドキュメント化されてない(ソースコードを見ないと分からない)、ソースコードは変更される可能性がある、将来ネイティブリソースが含まれる可能性はゼロではない(ゼロに近いとは思いますが)・・・ということを考えるべきです。

なので、IDisposable を継承するクラスは Dispose() を呼ぶべきというのが基本ルールであると思っています。

------ 2015/9/11 追記 ------

リンク先の MSDN ライブラリの記事を .NET Framework 4 のものに固定しました。URL にバージョンを指定しないと .NET 4.5 / 4.6 の MSDN ライブラリにリンクされますが、その記述が .NET 4 のものかなり異なっていて、.NET 4 をベースに書いた上の記事とミスマッチが生じましたので。

Tags: ,

ADO.NET

パラメータ d の値を復号

by WebSurfer 2013年4月12日 15:15

WebResource.axd や ScriptResource.axd のクエリ文字列のパラメータ d の値を復号化する方法を備忘録として書いておきます。

パラメータ d の値を復号

利用目的は、WebResource.axd や ScriptResource.axd に指定されているリソースを特定するためです。クエリ文字列のパラメータ d にはリソースが指定されています。しかし、パラメータ d は暗号化されているため、リソースを特定するためには復号しなければなりません。

内容は、先の記事「WebResource.axd の HTTP 404 エラー」で紹介したページのコードとほとんど同じですが、リンク切れになると困るので、主要な部分のみ抜き出しました。

上の画像を表示したコードは以下の通りです。このページを運用環境に含めたり、一般に公開したりすると、セキュリティ上の問題が生ずる恐れがありますので注意してください。

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Reflection" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="System.Text" %>

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

<script runat="server">
  protected void Button1_Click(object sender, EventArgs e)
  {
    string input = TextBox1.Text;
    if (string.IsNullOrEmpty(input))
    {
      Label1.Text = string.Empty;
      Label2.Text = string.Empty;
      return;
    }

    string pattern = "d=(?<param>[^&]+)&";
    Match match = Regex.Match(input, pattern);
    if (!match.Success)
    {
      Label1.Text = string.Empty;
      Label2.Text = string.Empty;
      return;
    }
    GroupCollection groups = match.Groups;
    string data = groups["param"].Value;        

    byte[] encryptedData =
        HttpServerUtility.UrlTokenDecode(data);
    if (encryptedData == null)
    {
      Label1.Text = data;
      Label2.BackColor = System.Drawing.Color.Red;
      Label2.Text = "無効なパラメータ";
      return;
    }
        
    Type machineKeySection = typeof(MachineKeySection);
    Type[] paramTypes = new Type[] { typeof(bool), 
                                     typeof(byte[]), 
                                     typeof(byte[]), 
                                     typeof(int), 
                                     typeof(int) };
    MethodInfo methodInfo = machineKeySection.GetMethod(
            "EncryptOrDecryptData",
            BindingFlags.Static | BindingFlags.NonPublic,
            null,
            paramTypes,
            null);

    try
    {
      byte[] decryptedData = (byte[])methodInfo.Invoke(
                null,
                new object[] { false, 
                               encryptedData, 
                               null, 
                               0, 
                               encryptedData.Length });

      string decrypted = Encoding.UTF8.GetString(decryptedData);
      TextBox1.Text = string.Empty;
      Label1.Text = data;
      Label2.BackColor = System.Drawing.Color.Lime;
      Label2.Text = decrypted;
    }
    catch (TargetInvocationException)
    {
      TextBox1.Text = string.Empty;
      Label1.Text = data;
      Label2.BackColor = System.Drawing.Color.Red;
      Label2.Text = "復号に失敗";
    }
  }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
  <title>d パラメータを復号</title>    
</head>
<body>
  <form id="form1" runat="server">
  <div>
    URL をコピー&ペースト
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" 
      runat="server" Text="復号" OnClick="Button1_Click" />
    <hr />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    <br />
    <asp:Label ID="Label2" runat="server"></asp:Label>
  </div>
  </form>
</body>
</html>

Tags:

ASP.NET

About this blog

2010年5月にこのブログを立ち上げました。主に ASP.NET Web アプリ関係の記事です。

Calendar

<<  2024年4月  >>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

View posts in large calendar