Add your own alternative version
Stats
182K views 2.2K downloads 54 bookmarked
Posted
8 Jun 2005
|
Comments and Discussions
|
|
Hi!
I found another little bug, sorry.
If you have more than one number box into the same page with different precision values, all objects takes as precision number the value of first object set.
Thanks again.
Best Regards
|
|
|
|
|
Great work, thank you very much!
I'm sorry, but i found a little bug.
Firefox hasn't window.event so it generate JavaScript error inside EnsureNumeric() function.
Please can you fix it?
Thanks again, Regards
|
|
|
|
|
This is great control, Could you please let me know how to fire Amountchange event of this control
|
|
|
|
|
Hi
I downloaded your source and built the project, great control!
The "load" event of the form, I set the property "Amount", eg "123", but the value print in control is always "0". Even with the code, I could not solve this problem. what can I do?
it works this way: "<st:NumberBox ID="txtPreco" runat="server" width="80" Amount="123"/>"
not so:
Protected Sub Page_Load (ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Me.IsPostBack = True Then Exit Sub
.
.
txtPreco.Amount = 123
.
.
End Sub
|
|
|
|
|
I spent the day wrestling with the Microsoft Ajax masked edit control. It just doesn't work for currency. Your control is great. I'm very impressed.
|
|
|
|
|
hi ,
we have added a new feature for the current number box.
i.e we are restricted the inout based on the format like if the format is (8,2)
then the input is restricted beyond these locations.
i.e example:
12345678.88 :entry completly restricted ,
12345678 : enrty restricted till we enter a '.' (dot seperator),
.99 : entry restricted after the . dot seperator as the precesion is 2. but can enter before
dot seperator
but the problem is when i select textbox and try to press the number, it is not clearing the numbers. which is a problem ..
i.e consider i enter 12345678.99 or .00 or 12345678 ,
and and select the content it does not allow to enter as the cursor position is in the end , and it has to restirict .
so is there any way i could aviod this .
i.e is there any way i could check in the script that if the data in textbox is selected or not ?
so based on which i could allow the input to be cleared.
thanks in advance,,,,
Thanks and Regards,
sriharsha
|
|
|
|
|
hi need help, in the number box when i set precision value to 4 why is it always round up to precision 2
|
|
|
|
|
It works great with any culture. Really saved my day. Thank you so much.
|
|
|
|
|
just spent the last hr resolving a javascript issue which arises due to ie's nonstandard way of handling events (using window.event vs an event object) - which breaks Firefox.
to fix this issue, in scripts.cs (around line 517) update your code to be
<br />
script.Append(ScriptHelper.BeginScriptFunction(ENSURE_NUMERIC, "evt"));<br />
script.Append("evt = (evt) ? evt : (window.event) ? event : null;");<br />
script.Append("if (evt)");<br />
script.Append("{");<br />
script.Append(" var charCode = (evt.charCode) ? evt.charCode :((evt.keyCode) ? evt.keyCode :((evt.which) ? evt.which : 0));");<br />
script.Append("}");<br />
script.Append("if(!((charCode>47&&charCode<58)||charCode==");<br />
script.Append(separator.ToString());<br />
script.Append("||charCode==");<br />
script.Append(minusSign.ToString());<br />
script.Append("))");<br />
script.Append("{evt.returnValue=false;}");<br />
script.Append(ScriptHelper.EndScriptFunction());<br />
page.RegisterClientScriptBlock(ENSURE_NUMERIC, script.ToString());<br />
Also, on line 398 in NumericControl.cs, make sure to update the keypress to send the event-
string onKeyPress = "EnsureNumeric(event)";<br />
Hope that saves someone out there an hr of their life 
|
|
|
|
|
First off thanks for sharing
I downloaded the source (zip file) and opened it there was nothing inside
Kevin S. Gallagher
Programming is an art form that fights back
|
|
|
|
|
Muito bom!
Very good!!!!!!
Stiven
|
|
|
|
|
Just started using this control. It works nice.
But, I would like to set the localization programatically - not read the web.config file. What if I want to handle multiple currencies on my site? As is, I cannot.
Also, I would like the option to have the textbox be blank without the $0.00 default. And of course a blank textbox would infer an Amount = 0.
Would it be possible for you to update the control for this?
|
|
|
|
|
OK, so I did it myself. Much improved from original. Thanks for the base code.
|
|
|
|
|
Hi, I'd like to know how can i implement a read-only property for this great control.
thanks.
fsdfsdf
|
|
|
|
|
Excellent!
I just added my custom additional validations (implementing the ivalidator interface) and my own binding to and from my form (implementing the IDataBoundControl interface) and the controls work very well.
Steve did a very nice job.
Rick.
Numeric Control:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.ComponentModel;
namespace SandTrap.WebControls
{
/// <summary>
/// Serves as the Base class for all numeric controls in the
/// SandTrap.WebControls namespace.
///
public class NumericControl : WebControl, IDataBoundControl, IValidator
{
#region .Declarations
// Properties
protected TextAlign _Alignment;
protected int _Precision;
protected decimal _MinAmount;
protected decimal _MaxAmount;
// TODO: Use styles for positive/negative values?
protected Color _NegativeColor;
protected Color _PositiveColor;
protected string _OnFocus;
protected string _OnKeyPress;
protected string _OnBlur;
private string _propertyName = string.Empty;
private string _dataMember =string.Empty;
private bool _allowzero = true;
private bool _valid = true;
private string _errorMessage=string.Empty;
// Events
[Browsable(true), Category("Action")]
public event EventHandler AmountChanged;
#endregion // Declarations
#region .Constructor
/// <summary>
/// Initialises a new instance of the NumericControl class.
///
protected NumericControl()
{
// Set default properties
_Alignment = TextAlign.Right;
_MinAmount = -100000000M;
_MaxAmount = 100000000M;
_Precision = 2;
_NegativeColor = Color.Red;
_OnFocus = string.Empty;
_OnKeyPress = string.Empty;
_OnBlur = string.Empty;
}
#endregion // Constructor
#region .Properties
/// <summary>
/// Gets or sets the alignment of the text in the control.
///
/// <value>
/// One of the TextAlign values. The default is right.
///
[
DefaultValue(typeof(TextAlign),"Right"),
Category("Appearance"),
Bindable(false),
Description("The alignment of text in the control")
]
public TextAlign Alignment
{
get
{
return _Alignment;
}
set
{
_Alignment = value;
}
}
public string ControlPropertyName
{
get
{
return _propertyName;
}
set
{
_propertyName = value;
}
}
public string SourceDataMember
{
get
{
return _dataMember;
}
set
{
_dataMember = value;
}
}
//To verify mandatory amounts. ricpue 01/19/2006
public bool AllowZero
{
get { return _allowzero; }
set { _allowzero = value; }
}
public bool IsValid
{
get { return _valid; }
set
{
_valid = value;
if (!_valid)
{
this.CssClass="error";
}
else
{
this.CssClass="input";
}
}
}
public string ErrorMessage
{
get { return _errorMessage; }
set { _errorMessage = value; }
}
/// <summary>
/// Gets of sets the amount.
///
/// <value>
/// A System.Decimal. The default is 0.
///
[
DefaultValue(typeof(decimal),"0"),
Category("Appearance"),
Bindable(true),
Description("The amount displayed in the control")
]
public decimal Amount
{
get
{
// Check if a value has been assigned
object amount = ViewState["amount"];
if (amount == null)
// Return the default
return 0M;
else
// Return the value
return (decimal)amount;
}
set
{
ViewState["amount"] = value;
// Set the text colour
if (value < 0)
base.ForeColor = NegativeColor;
else
base.ForeColor = PositiveColor;
}
}
/// <summary>
/// Gets the colour of the text.
///
/// <remarks>
/// The implementation hides the base class ForeColor property and implements it
/// as readonly. It returns PositiveColor if Amount is positive or NegativeColor
/// if Amount is negative.
///
[
Browsable(false)
]
public new Color ForeColor
{
get
{
return base.ForeColor;
}
}
/// <summary>
/// Gets of sets the minumum allowable amount.
///
/// <value>
/// A System.Decimal. The default is -100,000,000.00
///
[
DefaultValue(typeof(decimal),"-100000000"),
Category("Appearance"),
Bindable(true),
Description("The minumum allowable amount")
]
public decimal MinAmount
{
get
{
return _MinAmount;
}
set
{
_MinAmount = value;
}
}
/// <summary>
/// Gets of sets the maximum allowable amount.
///
/// <value>
/// A System.Decimal. The default is 100,000,000.00
///
[
DefaultValue(typeof(decimal),"100000000"),
Category("Appearance"),
Bindable(true),
Description("The maximum allowable amount")
]
public decimal MaxAmount
{
get
{
return _MaxAmount;
}
set
{
_MaxAmount = value;
}
}
/// <summary>
/// Gets or sets the text color if the Amount is negative.
///
/// <value>
/// A System.Drawing.Color. The default is Color.Red.
///
/// <remarks>
/// The property sets a user defined attribute (negativeColor). The attribute
/// is read by the rendered HTMLInputText controls onblur event to set the text
/// colour if its value is negative.
///
[
DefaultValue(typeof(Color),"Red"),
Category("Appearance"),
Bindable(true),
Description("The colour of negative currency values")
]
public Color NegativeColor
{
get
{
return _NegativeColor;
}
set
{
_NegativeColor = value;
// Set the controls ForeColor if appropriate
if (Amount < 0)
base.ForeColor = value;
}
}
/// <summary>
/// Gets or sets the name of the client script function(s) to call when the
/// control loses focus.
///
/// <value>
/// A System.String. The default is String.Empty.
///
/// <remarks>
/// All controls inheriting from NumericControl assign a script function to the
/// OnBlur event. This property allows additional script functions to be assigned
/// to the HTML controls OnBlur event
///
[
Category("Client Scripts"),
Description("The name of the client script function(s) to call when the " +
"control loses focus")
]
public string OnBlur
{
get
{
return _OnBlur;
}
set
{
_OnBlur = value;
}
}
/// <summary>
/// Gets or sets the name of a client script function to call when the
/// control gains focus.
///
/// <value>
/// A System.String. The default is String.Empty.
///
/// <remarks>
/// All controls inheriting from NumericControl assign a script function to the
/// OnBlur event. This property allows additional script functions to be assigned
/// to the HTML controls OnFocus event
///
[
Category("Client Scripts"),
Description("The name of the client script function(s) to call when the " +
"control gains focus")
]
public string OnFocus
{
get
{
return _OnFocus;
}
set
{
_OnFocus = value;
}
}
/// <summary>
/// Gets or sets the name of a client script function to call when the
/// control receives key press events.
///
/// <value>
/// A System.String. The default is String.Empty.
///
/// <remarks>
/// All controls inheriting from NumericControl assign a script function to the
/// OnKeyPress event. This property allows additional script functions to be assigned
/// to the HTML controls OnFocus event
///
[
Category("Client Scripts"),
Description("The name of the client script function(s) to call when the " +
"control receives key press events")
]
public string OnKeyPress
{
get
{
return _OnKeyPress;
}
set
{
_OnKeyPress = value;
}
}
/// <summary>
/// Gets or sets the text color if the Amount is positive.
///
/// <value>
/// A System.Drawing.Color. The default is Color.Empty.
///
/// <remarks>
/// The property sets a user defined attribute (positiveColor). The attribute
/// is read by the rendered HTMLInputText controls onblur event to set the text
/// colour if its value is positive.
///
[
DefaultValue(typeof(Color),"Empty"),
Category("Appearance"),
Bindable(true),
Description("The colour of negative currency values")
]
public Color PositiveColor
{
get
{
return _PositiveColor;
}
set
{
_PositiveColor = value;
// Set the controls ForeColor if appropriate
if (Amount >= 0)
{
base.ForeColor = value;
}
}
}
/// <summary>
/// Gets of sets the number of decimal digits to display.
///
/// <value>
/// A System.Int32. The default is 2.
///
[
DefaultValue(typeof(int),"2"),
Category("Appearance"),
Bindable(true),
Description("The number of decimal digits to display")
]
public int Precision
{
get
{
return _Precision;
}
set
{
_Precision = value;
}
}
#endregion // Properties
#region .Protected methods
/// <summary>
/// Adds HTML attributes and styles that need to be rendered.
///
/// <param name="writer">
/// A System.Web.UI.HtmlTextWriter that represents the output stream to render
/// HTML content on the client
///
/// <remarks>
/// The method overrides the base class to add the attributes necessary to
/// render the control as as text input.
///
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
// Add attributes necessary to display an text control
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");
writer.AddAttribute(HtmlTextWriterAttribute.Name, UniqueID);
writer.AddStyleAttribute("text-align", Alignment.ToString());
// Add user defined attributes to control colour formatting
writer.AddAttribute("negativeColor", NegativeColor.Name);
if (PositiveColor != Color.Empty)
{
writer.AddAttribute("positiveColor", PositiveColor.Name);
}
// Add user defined attributes to control minimum and maximum values
writer.AddAttribute("minAmount", MinAmount.ToString());
writer.AddAttribute("maxAmount", MaxAmount.ToString());
// Add client side event handlers
string onKeyPress = "EnsureNumeric()";
if (OnKeyPress != string.Empty)
{
onKeyPress += "," + OnKeyPress;
}
writer.AddAttribute("onkeypress", onKeyPress);
}
/// <summary>
/// Returns the System.Web.UI.HtmlTextWriterTag.
///
/// <remarks>
/// The method overrides the base class (Span tag) to return the
/// Input (TextField) tag.
///
protected override HtmlTextWriterTag TagKey
{
get
{
return HtmlTextWriterTag.Input;
}
}
/// <summary>
/// Raises the AmountChanged event.
///
/// <param name="e">
/// A System.EventArgs that contains event information.
///
/// <remarks>
/// The control must have view state enabled for the AmountChanged event to work
/// correctly.
///
protected virtual void OnAmountChanged(EventArgs e)
{
// Check for registered objects
if (AmountChanged != null)
{
// Notify the object
AmountChanged(this, e);
}
}
/// <summary>
/// Raises the PreRender event.
///
/// <param name="e">
/// A System.EventArgs that contains event information.
///
/// <remarks>
/// The method overrides the base class to register the EnsureNumeric script.
///
protected override void OnPreRender(System.EventArgs e)
{
// Register the EnsureNumeric script
Scripts.RegisterEnsureNumericScript(Page);
// Call the base method
base.OnPreRender(e);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.Validators.Add(this);
}
protected override void OnUnload(EventArgs e)
{
if (Page != null)
{
Page.Validators.Remove(this);
}
base.OnUnload(e);
}
public virtual void Validate()
{
this.IsValid = true;
if (!this.AllowZero)
{
if (this.Amount == 0)
{
this.IsValid = false;
return;
}
}
}
#endregion // Protected methods
}
}
Form:
Loan Amount $
<customcontrols:currencybox id="Lock_LoanAmount1" runat="server" SourceDataMember="Lock_LoanAmount1" ControlPropertyName="Amount"
CssClass="input" AllowZero="False" MinAmount="0">
*
And code behind (after submitting the form):
private void savelock_Click(object sender, System.EventArgs e)
{
if (Page.IsValid==false)
{displayErrorMsg();return;}
else
{lblerrorpage.Text = String.Empty;lblerrorpage.Visible=false;}
Web.DataBinder.Bind(this, ratelock, Web.BindingDirection.ToDataSource);
}
Rick P.
-- modified at 14:41 Thursday 19th January, 2006
|
|
|
|
|
Is it possible to use Currency TextBox inside a FormView (Asp.net 2.0), and the amount property databinded ?
Thanks
|
|
|
|
|
Hi, I have the same question.
I has try 2 different line to bind to a datalist:
<!-- st:CurrencyBox ID="txtCost" Text='<%# DataBinder.Eval(Container.DataItem, "Cost") %>' runat="server" Width="80px" MinAmount="0" -->
and
<!-- st:CurrencyBox ID="txtCost" Amount='<%# DataBinder.Eval(Container.DataItem, "Cost") %>' runat="server" Width="80px" MinAmount="0" -->
I get error in compiling. Hope the author has some new tricks.
Email to ntgraph@yahoo.com
-- modified at 22:59 Monday 24th July, 2006
|
|
|
|
|
Hi,
tried using the Numeric Textbox, great & works cool,except for the following bug
When there are 2 numeric textboxes in the same page with different precision set,
Initial display it is fine, but the onBlur() of the second Numeric textbox, the precision is set to the what has been given for the first.
Checked the source, and found that the FormatDecimalAsNumber() is calling the DecimalToNumber() with the precision value of the first rendered control.
Hope i am clear.
Regards,
Baskar
|
|
|
|
|
Thanks Baskar,
Problem is solved by writing the precision property as an attribute, and retrieving its value in the script. I'll update the project when I'm back from holidays late January, but if you wish to update yourself:
In NumericControl class
protected override void AddAttributesToRender(HtmlTextWriter writer)<br />
{<br />
...<br />
(following line added)<br />
writer.AddAttribute("precision", Precision.ToString());<br />
...<br />
}
and in NumberBox class (and similar for PercentBox and CurrencyBox classes)
private void RegisterFormatNumberScripts(Page page)<br />
{<br />
...<br />
script.Append("var p=c.getAttribute('precision');");<br />
script.Append("c.value=DecimalToNumber(c.value,p);");<br />
...<br />
}
Stephen
|
|
|
|
|
Hi Steve,
I already did that & added the following things :
1. Not to accept more than one decimal point
2. Accept a -ve sign only at the beginning (and, of course, no two -ve sign)
Thanks once again for a very good control.
Baskar
|
|
|
|
|
Hi,
Found another issue after implementing the above said.
During design time i gave the precision to be 2 and based on certain user input, the precision i changed to 3. (Real life scenario -- Currencies Bahrain Dinar & Omani Riyal has 3 digit accuracies)
After a postback, the amount is rounded 2 digit automatically, but when when I saw the View Source, the precison was 3 intact. I feel the precison is lost somewhere after a postback when it is set programmatically.
Can you help me out? Thanks in advance,
Baskar
|
|
|
|
|
Hi,
I've been using your control extensively - and think its the business. However, I have run into a small problem.
I added the attributes: [SupportsEventValidation(), System.Web.UI.ValidationProperty("Amount")] to the NumericControl class, and the "control to validate" now appears as an option for a CompareValidator. I set the code as follows:
<st:numberbox id="NumberBox1" runat="server" minamount="0"></st:numberbox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="NumberBox1" CultureInvariantValues="True" ErrorMessage="Value cannot be zero" Operator="GreaterThan" Type="Double" ValueToCompare="0">*</asp:CompareValidator>
The CompareValidator correctly validates the Amount of the number control.
However, if I now add a <asp:ValidationSummary ID="ValidationSummary1" runat="server" /> to the page, the ValidationSummary works OK for unformatted Amounts, i.e. up to 999.99, but fails on formatted numbers, i.e. 1,002.67.
I appreciate that this is not a problem with your control, and guess its a bug in the asp:ValidationSummary. Nonetheless, do you have any ideas on how one could get arround this?
Many thanks in advance
Jeremy Holt
|
|
|
|
|
Thanks Jeremy,
Unsure how to solve this and will have to do some testing.
I'm about to go on holidays, so will need to put on hold until end of January.
Stephen
|
|
|
|
|
Steve,
Actually I wrote a simple CompareValidator control to work with the number box.
What was happening is that the "out of the box" CompareValidator correctly reads the numeric value of the textbox (or your control), i.e. it parses 6.5% to 0.065 - this happens when the textbox loses focus. However, just prior to the page being posted back to the server, the ValidationSummary control asks the CompareValidator control to revalidate the contents of the textbox, however insted of reading the parsed value of the textbox it sends the literal contents of the textbox, i.e. 6.5%.
You can see this clearly if you put a CustomValidator on the control and read Args.Value when the textbox loses focus, and again when the ValidatorSummary is called.
This is definitely not a problem with your control - I guess its a bug in the out of the box controls.
Best regards
Jeremy
|
|
|
|
|
Jeremy, can you post your code for the validator you wrote? We are trying to use a RangeValidator and are experiencing the same anomaly that you discussed earlier.
Thanks!!
|
|
|
|
|
|
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
|