|
<< Click to Display Table of Contents >> ValorTextBox |
![]() ![]()
|
Descrição
Um TextBox com:
•Entrada de valores com 2 casas decimais
•Formata durante a digitação: 1.234,45
•Métodos SetValor() e GetValor()
Tela

ValorTextBox.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ValorTextBox.ascx.cs" Inherits="ValorTextBox" %>
<script type="text/javascript" src="util/formatacao.js"></script>
<asp:TextBox ID="VlrTextBox" runat="server" onKeyPress="return(Moeda(this,event))"></asp:TextBox>
ValorTextBox.ascx.cs
using System;
public partial class DataTextBox : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void SetDate(DateTime data)
{
DtTextBox.Text = data.ToString("dd/MM/yy");
}
public DateTime GetDate()
{
DateTime data;
if (!DateTime.TryParse(DtTextBox.Text, out data))
data = new DateTime(1900, 1, 1);
return data;
}
public bool IsEmpty()
{
DateTime data;
if (!DateTime.TryParse(DtTextBox.Text, out data))
return true;
else
return false;
}
}
formatacao.js
function Moeda(campo, e) {
var SeparadorDecimal = ","
var SeparadorMilesimo = "."
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true;
key = String.fromCharCode(whichCode); // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false; // Chave inválida
len = campo.value.length;
for (i = 0; i < len; i++)
if ((campo.value.charAt(i) != '0') && (campo.value.charAt(i) != SeparadorDecimal)) break;
aux = '';
for (; i < len; i++)
if (strCheck.indexOf(campo.value.charAt(i)) != -1) aux += campo.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) campo.value = '';
if (len == 1) campo.value = '0' + SeparadorDecimal + '0' + aux;
if (len == 2) campo.value = '0' + SeparadorDecimal + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += SeparadorMilesimo;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
campo.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
campo.value += aux2.charAt(i);
campo.value += SeparadorDecimal + aux.substr(len - 2, len);
}
return false;
}
Importante: observações para usar
Não esqueça de acrescentar no aspx:
<%@ Register src="~/UserControls/ValorTextBox.ascx" tagname="ValorTextBox" tagprefix="uc1" %>
Para usar:
<uc1:ValorTextBox ID="ValorTextBox1" runat="server" />
Nos meus testes, coloquei esse controle numa subpasta "UserControls" e tive assim que ajustar o caminho para o js no ValorTextBox.ascx:
<script type="text/javascript" src="/UserControls/formatacao.js"></script>