Kobarin's Development Blog

C#やASP.NETなどについての記録です。

App_Codeでコントロールを定義する

App_Codeフォルダ配下に追加したコントロールを使用する方法。

~/App_Code/webusercontrol.cs

using System;
using System.Text.RegularExpressions;

namespace webusercontrol
{
  /// 
  /// 
  /// 
  public class LabelNumeric : System.Web.UI.WebControls.Label
  {
    string strText = "";

    /// 
    /// can input only numeric characters
    /// 
    public string Text
    {
      set
      {
        Regex reg = new Regex("[^0-9]");
        strText = reg.Replace(value, "");
      }
      get { return strText; }
    }
  }
}

~/test.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="mycontrol.aspx.cs" Inherits="common_mycontrol" %>
<%@ Register TagPrefix="mycon" Namespace="webusercontrol" Assembly="__code" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
  <form id="form1" runat="server">
    <div>
      <mycon:LabelNumeric runat="server" ID="mylabel1" />
    </div>
  </form>
</body>
</html>

ポイントは、Registerタグ内の「Assembly="__code"」。