動的にコントロールを生成しリストに格納して参照する - ASP.NET

ASP.NETで動的にコントロールを生成しリストに格納して参照するコードを紹介します。

概要

こちらの記事ではASP.NETで動的にコントロールを生成するコードを紹介しました。コントロールの数が少ない場合は紹介した方法で問題はないのですが、生成されるコントロールの数が増え、すべてのコントロールに対して処理を実行したい場合は、変数での参照ではコードの記述が冗長になります。まとめて処理をする場合は、配列やリストに格納して処理したほうがシンプルに記述できます。この記事では、動的に生成したコントロールをリストに格納して参照するコードを紹介します。

プログラム例

ASP.NETアプリケーションを作成します。

UI

下図のWebフォームを作成します。Webフォームにボタン2つとPlaceholder, Label を配置します。


aspxファイルのコードは下記になります。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ControlGenerateStoreList.aspx.cs" Inherits="GenerateControl.ArrayControlGenerate" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title></title>
  <link rel="stylesheet" href="ControlGenerateStoreList.css" />
</head>
<body>
  <div class="head">ヘッダ</div>
  <form id="form1" runat="server">
    <div>
      <div>
        <asp:Button ID="Button1" runat="server" Text="Button1" OnClick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="Button2" OnClick="Button2_Click" />
      </div>
      <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
      <hr />
      <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
  </form>
  <div class="foot">フッタ</div>
</body>
</html>

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GenerateControl
{
  public partial class ArrayControlGenerate : System.Web.UI.Page
  {
    List<TextBox> TextBoxList = new List<TextBox>();

    protected void Page_Load(object sender, EventArgs e)
    {
    
    }

    protected void Page_PreInit(object sender, EventArgs e)
    {
      for (int i = 0; i < 24; i++) {
        TextBox tb = new TextBox();
        PlaceHolder1.Controls.Add(tb);
        TextBoxList.Add(tb);
      }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
      Label1.Text = "18番目のテキストボックスの値:" + TextBoxList[17].Text;
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
      foreach (TextBox t in TextBoxList) {
        t.Text = "";
      }
    }
  }
}

解説

ページ表示時に下記のコードが実行されます。forループにより、TextBoxを24個生成します。生成したTextBoxはPlaceHolder1に配置されます。また、生成されたTextBoxのオブジェクトをList<TextBox>型のTextBoxListに追加します。
protected void Page_PreInit(object sender, EventArgs e)
{
  for (int i = 0; i < 24; i++) {
    TextBox tb = new TextBox();
    PlaceHolder1.Controls.Add(tb);
    TextBoxList.Add(tb);
  }
}

[Button1]をクリックすると下記コードが実行されます。下記のコードでは、TextBoxListのリストの18番目の要素のテキストボックスに入力されている値をLabel1に表示します。
protected void Button1_Click(object sender, EventArgs e)
{
  Label1.Text = "18番目のテキストボックスの値:" + TextBoxList[17].Text;
}

[Button2]をクリックすると下記コードが実行されます。foreach文でTextBoxListのすべてのTextBoxオブジェクトに対して、Textプロパティの値を空文字に設定します。この処理により、[Button2]をクリックすると動的に生成されたすべてのテキストボックスの入力されている文字列が消去されます。
protected void Button2_Click(object sender, EventArgs e)
{
  foreach (TextBox t in TextBoxList) {
    t.Text = "";
  }
}

実行結果

プロジェクトを実行します。Webブラウザが起動し、下図のページが表示されます。


18番目のテキストボックスに文字を入力します。(今回は「ぺんぎん」の文字列を入力しています。)
入力後[Button1]をクリックします。Label1にテキストボックスに入力した文字列が表示されます。


テキストボックスにいろいろ値を入力します。


[Button2]をクリックします。すべてのテキストボックスの値が消去されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-01-06
作成日: 2018-03-27
iPentec all rights reserverd.