2011年9月17日土曜日

ASP.NET TextBoxで数値のみ入力可能なカスタムコントロールの作成方法

今回作成したカスタムコントロールは下記の通りです。
テキストボックスを継承して新しいカスタムコントロールを作成しています。
下記ソースはIMEをoffにしてJavaScriptを使用して数値のみの入力としています。

dllも添付していますので、ご自由に使用してください。
本来は、プロパティでIMEの変更等を行いたかったのですが、
うまいこと動かなかったのでIME等の設定は決め打ちで行っています。
ソースも一応貼り付けていますが、そのまま動くかは不明です。
(改行等でブログの仕様で文字等がおかしくなってる場合があります。)

Browsable(False)>を宣言するとプロパティに表示しません。

 


 

Imports System.ComponentModel
Imports System.Web.UI

<DefaultProperty("Text"), ToolboxData("<{0}:TextBox_ImrOff_NumOnly runat=server></{0}:TextBox_ImrOff_NumOnly>")> _

Public Class TextBox_ImrOff_NumOnly
    Inherits System.Web.UI.WebControls.TextBox
    Private _imeMode = "disabled"
    Private _onFocus As String = "javascript:this.value" _
                "=this.value.replace(/,/g,'');this.select();this.style.backgroundColor='#FFFFCC'"
    Private _onBlur As String = "javascript:if(isNaN(this.value)==true){ alert('数値のみ入力可です。');" _
                "this.focus();return};this.value=this.value-0;while(this.value!=(tmpStr=this.value.replace(/^([+-]?\d+)(\d\d\d)/,'$1,$2'))){this.value=tmpStr;};if(this.value=='') this.value='0';" _
            "this.style.backgroundColor='#FFFFFF'"
    Private _onkeyPress As String = "javascript:if(((event.keyCode<48)||(event.keyCode>57))&&(event.keyCode!=45)&&(event.keyCode!=46)){window.event.returnValue=false;}"

    <Browsable(False)> _
    Public Property ImeMode() As String
        Get
            Return _imeMode
        End Get
        Set(ByVal Value As String)
            _imeMode = Value
        End Set
    End Property

 

    'フォーカス取得時のプロパティ設定
    <Browsable(False)> _
    Public Property onFocus() As String
        Get
            Return _onFocus
        End Get
        Set(ByVal Value As String)
            _onFocus = Value
        End Set
    End Property

 

    'フォーカス喪失時のプロパティ設定
    <Browsable(False)> _
    Public Property onBlur() As String
        Get
            Return _onBlur
        End Get
        Set(ByVal Value As String)
            _onBlur = Value
        End Set
    End Property

 

    'キー押下時のプロパティ設定
    <Browsable(False)> _
    Public Property onkeyPress() As String
        Get
            Return _onkeyPress
        End Get
        Set(ByVal Value As String)
            _onkeyPress = Value
        End Set
    End Property

 

    'プロパティ追加
    Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
        MyBase.OnInit(e)
        MyBase.Style("ime-mode") = _imeMode
        'MyBase.Style("text-align") = _alignList(_align)
    End Sub

 

    Protected Overrides Sub AddAttributesToRender(ByVal writer As System.Web.UI.HtmlTextWriter)
        writer.AddAttribute("onFocus", _onFocus)
        writer.AddAttribute("onBlur", _onBlur)
        writer.AddAttribute("onkeyPress", _onkeyPress)
        MyBase.AddAttributesToRender(writer)
    End Sub
End Class


 


 


ASP.NET VB2005 カスタムコントロール





0 件のコメント:

コメントを投稿