一个小数点后两位的数值类型的控件

因为项目需要,写了一个数值控件,需求是可以写入小数点后两位的数值,其他不能输入。代码如下:

AmountTextBox

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControlsEx
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:AmountTextBox runat=server></{0}:AmountTextBox>")]
public class AmountTextBox : TextBox
{
[Bindable(true)]
[DefaultValue("")]
public override string Text
{
get
{
return base.Text;
}
set
{
if (!string.IsNullOrEmpty(value))
{
base.Text = value;
}
else
{
base.Text = string.Empty;
}
}
}
[Bindable(true)]
[DefaultValue("")]
public decimal? Value
{
get
{
if (string.IsNullOrEmpty(base.Text))
{
return null;
}
else
{
return Convert.ToDecimal(base.Text.Replace(",", string.Empty));
}
}
set
{
if (value.HasValue)
{
//base.Text = value.Value.ToString("#,##0.#0");
base.Text = value.Value.ToString("#,##0.##");
}
else
{
base.Text = null;
}
}
}

[DefaultValue("")]
public string OnClientBlur
{
get
{
if (ViewState["OnClientBlur"] != null)
{
return ViewState["OnClientBlur"].ToString();
}
else
{
return string.Empty;
}
}
set
{
ViewState["OnClientBlur"] = value;
}
}

protected override void Render(HtmlTextWriter writer)
{
if (!string.IsNullOrEmpty(this.Attributes["onblur"]))
{
this.OnClientBlur = this.Attributes["onblur"];
this.Attributes["onblur"] = string.Empty;
}

this.Attributes["onfocus"] = "return jsAmountControl_focus(this);";
this.Attributes["onblur"] = "return jsAmountControl_blur(this);";
if (!string.IsNullOrEmpty(this.OnClientBlur))
{
this.Attributes["onblur"] = "if(jsAmountControl_blur(this)){return " + this.OnClientBlur + ";}";
}
else
{
this.Attributes["onblur"] = "return jsAmountControl_blur(this);";
}
base.Render(writer);
}
}
}

转载请注明:代码家园 » 一个小数点后两位的数值类型的控件

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)