Accueil > > > CURRENCY TEXTBOX - TEXTBOX DE SAISIE DE MONTANT.
CURRENCY TEXTBOX - TEXTBOX DE SAISIE DE MONTANT.
Information sur la source
Description
Petite classe permettant la saisie de montant en respectant les contraintes spécifiques liées aux cultures. (Symbol, nombres de décimal)
Source
- #region Using
- using System;
- using System.Windows.Forms;
- using System.Globalization;
- using System.Drawing;
- #endregion Using
-
- namespace CS.TextBoxes
- {
-
- [ToolboxBitmap(typeof(TextBox))]
- /// <summary>
- /// Provides a control allowing typing only currency values.
- /// This control supports Culture-specific constraints.
- /// </summary>
- public class CurrencyTextBox : TextBox
- {
- #region Fields
- private CultureInfo _culture = System.Globalization.CultureInfo.CurrentUICulture;
- private int _digitsCount = System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.CurrencyDecimalDigits;
- private string separator;
- private bool overridesCulture;
- #endregion Fields
-
- #region Constructors
- /// <summary>
- /// Initialiazes a new instance of <see cref="CurrencyTextBox"/>.
- /// </summary>
- public CurrencyTextBox()
- {
- separator = _culture.NumberFormat.CurrencyDecimalSeparator;
- }
-
- #endregion Constructors
-
- #region Key events
- protected override void OnKeyPress(KeyPressEventArgs e)
- {
- int sepIndex = this.Text.IndexOf(separator);
- double val = TryParseCurrency(this.Text, !overridesCulture);
- int digits = CountDigits();
-
- if (char.IsNumber(e.KeyChar) || char.IsControl(e.KeyChar))
- {
- if (digits >= _digitsCount && SelectionStart > sepIndex + digits) //we have not reached the max digits
- {
- e.Handled = true;
- }
- else
- {
- if (char.IsNumber((char)e.KeyChar) && val == 0)
- {
- this.Text = e.KeyChar.ToString(_culture);
- this.SelectionStart += 1;
- e.Handled = true;
- }
- else //Value was not 0
- base.OnKeyPress(e);
- }
- }
- else
- {
- //We entered the separator char
- if (separator.StartsWith(e.KeyChar.ToString(_culture)))
- this.SelectionStart = this.Text.IndexOf(separator) + 1;
-
- //We entered the negative char
- else if (e.KeyChar == '-')
- this.Text = (-val).ToString(_culture);
-
- e.Handled = true;
- }
-
- }
-
- protected override void OnTextChanged(EventArgs e)
- {
- base.OnTextChanged(e);
- int cursorPos = this.SelectionStart;
-
- if (cursorPos < 0)
- return;
-
- int count = CountGroups(this.Text, _culture);
-
- base.Text = DoubleToStringCurrency(TryParseCurrency(this.Text, !overridesCulture), !overridesCulture);
-
- // adujst caret position
- this.SelectionStart = cursorPos + CountGroups(this.Text, _culture) - count;
- }
-
- #endregion Key events
-
- #region Helpers
- private int CountDigits()
- {
- int sepIndex = this.Text.IndexOf(separator) + 1; //index start to 0
- return IsCurrencySymbolBefore ? this.Text.Trim().Length - sepIndex : this.Text.Trim().Length - 1 - sepIndex;
- }
- private string DoubleToStringCurrency(double d, bool useCultureFormat)
- {
- if (useCultureFormat)
- {
- return d.ToString("C", _culture);
- }
- else
- {
- return d.ToString("C" + _digitsCount.ToString(_culture));
- }
- }
-
- private double TryParseCurrency(string text, bool useCultureFormat)
- {
- double d;
- if( useCultureFormat)
- {
- double.TryParse(text, System.Globalization.NumberStyles.Currency, _culture, out d);
- }
- else
- {
- NumberStyles s = NumberStyles.AllowThousands | NumberStyles.AllowTrailingWhite | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol;
- double.TryParse(text, s, _culture, out d);
- }
- return d;
- }
-
- private bool IsCurrencySymbolBefore
- {
- get
- {
- return char.IsSymbol(this.Text[0]);
- }
- }
-
- /// <summary>
- /// Coint number of groups in value.
- /// </summary>
- /// <param name="value"></param>
- /// <param name="format">CultureInfo containing number format</param>
- /// <returns>Groups count.</returns>
- private static int CountGroups(string value, CultureInfo format)
- {
- int count = 0;
- NumberFormatInfo nfi = format.NumberFormat;
-
- for(int i = 0; i < value.Length - 1 ; ++i)
- if(value[i] == nfi.NumberGroupSeparator[0])
- count++;
-
- return count;
- }
- #endregion Helpers
-
- #region Properties
- /// <summary>
- /// Gets or sets the culture associated to textbox.
- /// </summary>
- public System.Globalization.CultureInfo Culture
- {
- get { return this._culture; }
- set
- {
- double d = TryParseCurrency(this.Text, !overridesCulture);
-
- if (value.IsNeutralCulture)
- value = CultureInfo.InvariantCulture;
-
- this._culture = value;
-
- _digitsCount = value.NumberFormat.CurrencyDecimalDigits;
- separator = _culture.NumberFormat.CurrencyDecimalSeparator;
-
- this.Text = DoubleToStringCurrency(d, !overridesCulture);
- }
- }
-
- /// <summary>
- /// Gets or sets the number of decimals after separator.
- /// </summary>
- public int DigitsCount
- {
- get { return this._digitsCount; }
- set
- {
- this._digitsCount = value;
- overridesCulture = value != this._culture.NumberFormat.CurrencyDecimalDigits;
- }
- }
-
- /// <summary>
- /// Ovverides Text property to format string.
- /// </summary>
- public new string Text
- {
- get
- {
- return base.Text;
- }
- set
- {
- double empty = 0;
- base.Text = value.Trim().Length > 0 ? value : empty.ToString("C", _culture);
- this.SelectionStart = Convert.ToInt32(IsCurrencySymbolBefore);
- }
- }
-
- /// <summary>
- /// Gets or sets the numeric value of the represented string.
- /// </summary>
- public double Value
- {
- get
- {
- return TryParseCurrency(this.Text, !overridesCulture);
- }
- set
- {
- base.Text = value.ToString();
- this.SelectionStart = IsCurrencySymbolBefore ? 1 : 0;
- }
- }
- #endregion Properties
-
- }
- }
#region Using
using System;
using System.Windows.Forms;
using System.Globalization;
using System.Drawing;
#endregion Using
namespace CS.TextBoxes
{
[ToolboxBitmap(typeof(TextBox))]
/// <summary>
/// Provides a control allowing typing only currency values.
/// This control supports Culture-specific constraints.
/// </summary>
public class CurrencyTextBox : TextBox
{
#region Fields
private CultureInfo _culture = System.Globalization.CultureInfo.CurrentUICulture;
private int _digitsCount = System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.CurrencyDecimalDigits;
private string separator;
private bool overridesCulture;
#endregion Fields
#region Constructors
/// <summary>
/// Initialiazes a new instance of <see cref="CurrencyTextBox"/>.
/// </summary>
public CurrencyTextBox()
{
separator = _culture.NumberFormat.CurrencyDecimalSeparator;
}
#endregion Constructors
#region Key events
protected override void OnKeyPress(KeyPressEventArgs e)
{
int sepIndex = this.Text.IndexOf(separator);
double val = TryParseCurrency(this.Text, !overridesCulture);
int digits = CountDigits();
if (char.IsNumber(e.KeyChar) || char.IsControl(e.KeyChar))
{
if (digits >= _digitsCount && SelectionStart > sepIndex + digits) //we have not reached the max digits
{
e.Handled = true;
}
else
{
if (char.IsNumber((char)e.KeyChar) && val == 0)
{
this.Text = e.KeyChar.ToString(_culture);
this.SelectionStart += 1;
e.Handled = true;
}
else //Value was not 0
base.OnKeyPress(e);
}
}
else
{
//We entered the separator char
if (separator.StartsWith(e.KeyChar.ToString(_culture)))
this.SelectionStart = this.Text.IndexOf(separator) + 1;
//We entered the negative char
else if (e.KeyChar == '-')
this.Text = (-val).ToString(_culture);
e.Handled = true;
}
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
int cursorPos = this.SelectionStart;
if (cursorPos < 0)
return;
int count = CountGroups(this.Text, _culture);
base.Text = DoubleToStringCurrency(TryParseCurrency(this.Text, !overridesCulture), !overridesCulture);
// adujst caret position
this.SelectionStart = cursorPos + CountGroups(this.Text, _culture) - count;
}
#endregion Key events
#region Helpers
private int CountDigits()
{
int sepIndex = this.Text.IndexOf(separator) + 1; //index start to 0
return IsCurrencySymbolBefore ? this.Text.Trim().Length - sepIndex : this.Text.Trim().Length - 1 - sepIndex;
}
private string DoubleToStringCurrency(double d, bool useCultureFormat)
{
if (useCultureFormat)
{
return d.ToString("C", _culture);
}
else
{
return d.ToString("C" + _digitsCount.ToString(_culture));
}
}
private double TryParseCurrency(string text, bool useCultureFormat)
{
double d;
if( useCultureFormat)
{
double.TryParse(text, System.Globalization.NumberStyles.Currency, _culture, out d);
}
else
{
NumberStyles s = NumberStyles.AllowThousands | NumberStyles.AllowTrailingWhite | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol;
double.TryParse(text, s, _culture, out d);
}
return d;
}
private bool IsCurrencySymbolBefore
{
get
{
return char.IsSymbol(this.Text[0]);
}
}
/// <summary>
/// Coint number of groups in value.
/// </summary>
/// <param name="value"></param>
/// <param name="format">CultureInfo containing number format</param>
/// <returns>Groups count.</returns>
private static int CountGroups(string value, CultureInfo format)
{
int count = 0;
NumberFormatInfo nfi = format.NumberFormat;
for(int i = 0; i < value.Length - 1 ; ++i)
if(value[i] == nfi.NumberGroupSeparator[0])
count++;
return count;
}
#endregion Helpers
#region Properties
/// <summary>
/// Gets or sets the culture associated to textbox.
/// </summary>
public System.Globalization.CultureInfo Culture
{
get { return this._culture; }
set
{
double d = TryParseCurrency(this.Text, !overridesCulture);
if (value.IsNeutralCulture)
value = CultureInfo.InvariantCulture;
this._culture = value;
_digitsCount = value.NumberFormat.CurrencyDecimalDigits;
separator = _culture.NumberFormat.CurrencyDecimalSeparator;
this.Text = DoubleToStringCurrency(d, !overridesCulture);
}
}
/// <summary>
/// Gets or sets the number of decimals after separator.
/// </summary>
public int DigitsCount
{
get { return this._digitsCount; }
set
{
this._digitsCount = value;
overridesCulture = value != this._culture.NumberFormat.CurrencyDecimalDigits;
}
}
/// <summary>
/// Ovverides Text property to format string.
/// </summary>
public new string Text
{
get
{
return base.Text;
}
set
{
double empty = 0;
base.Text = value.Trim().Length > 0 ? value : empty.ToString("C", _culture);
this.SelectionStart = Convert.ToInt32(IsCurrencySymbolBefore);
}
}
/// <summary>
/// Gets or sets the numeric value of the represented string.
/// </summary>
public double Value
{
get
{
return TryParseCurrency(this.Text, !overridesCulture);
}
set
{
base.Text = value.ToString();
this.SelectionStart = IsCurrencySymbolBefore ? 1 : 0;
}
}
#endregion Properties
}
}
Sources du même auteur
Sources de la même categorie
Commentaires et avis
Discussions en rapport avec ce code source dans le forum
richtextbox avec images [ par boule ]
Bonjour, je souhaite inserer des images dans un textbox est ce que quelqu'un sait comment faire. Voila le pb je recois une chaine de caractere et selo
Réinitialiser complètement une application Windows [ par jeffwow ]
Ma Form comprend 84 TextBox ( un petit jeu de MasterMind ). Je souhaite pouvoir réinitialiser tous ces TextBox rapidement si le joueur veut recommenc
[C#] Nom de fichier dans un textBox [ par jeffwow ]
Donc, j'ouvre un fichier avec OpenFileDailog... jusque là ça va. Ensuite, je voudrais prendre le nom de ce fichier et l'envoyer dans un textBox. tex
afficher un int dans un textBox [ par petitours ]
Bonjour,Comme vous pouvez le deviner avec le titre de ce post, je suis un très grand débutant du C#...de la programmation d'ailleur...Ca fait depuis
SELECT et INSERT avec C# [ par GazGaz ]
lu alors voila je suis en train de créer une application dont le role sera de rechercher des informations se trouvants dans une base de données en sql
Accéder à une textBox depuis une autre classe [ par nicolson ]
Salut tout le monde :)En fait, je veux rajouter une phrase à une textbox depuis une autre classe que Form1.Si ma classe Test hérite de Form1, je peux
textBox dans une listView [ par pogo ]
bonjour,je cherche a faire qqchose qui me parait assez simple..mais qu en apparence uniquement!je voudrais remplacer (apres un click) le subitem d'un
Afficher uniquement des entiers dans une TextBox [ par Online ]
Salut, Voila, je souhaiterais faire une TextBox qui ne stockerai que des entiers (par exemples des années) mais je ne sais pas comment faire pour indi
Windows Form HELP !!! [ par CrAShGuN ]
Bonjours, Mon problème est que dans mon application j'ai 2 form avec des controles différents et je voudrais que sur la 2ème Form quand je tape par ex
Entier dans une textBox [ par Online ]
Encore et toujours moi, arfVoila, j'ai suivi la méthode pour n'afficher que les entiers dans une textBox, ce la fonctionne très bien, trop bien meme p
|
Derniers Blogs
[TECHDAYS2012] OUI J'Y SERAI![TECHDAYS2012] OUI J'Y SERAI! par JeremyJeanson
Bonsoir, Certes, je l'annonce avec un peu de retard, mais je serai effectivement au Techdays demain. Comme l'an dernier, je participerai au programme ATE (Ask The Expert). Si vous avez des questions Workflow, WCF, AppFabric ou plus généralement .net, n'hé...
Cliquez pour lire la suite de l'article par JeremyJeanson TFS INTEGRATION TOOLS - SUIVI DES SYNCHRONISATIONS AVEC REPORTING SERVICESTFS INTEGRATION TOOLS - SUIVI DES SYNCHRONISATIONS AVEC REPORTING SERVICES par vfabing
Afin de s'assurer du bon fonctionnement des différentes synchronisations effectuées par les TFS Integration Tools, 2 rapports sont présents dès l'installation. Il suffit alors d'effectuer les manipulations suivantes pour pouvoir les visualiser : Loca...
Cliquez pour lire la suite de l'article par vfabing CSS CONTENT STATE SELECTORS (PERSONNAL DRAFT)CSS CONTENT STATE SELECTORS (PERSONNAL DRAFT) par FREMYCOMPANY
Bonjour à tous, Je viens de publier une proposition comprenant 5 pseudo-classes pour le CSS Working Group ayant trait à l'état de chargement d'un élément (ex: IMG,VIDEO,AUDIO,OBJECT pour l'HTML.). Si le c½ur vous en dit, vous pouvez retrouver cette p...
Cliquez pour lire la suite de l'article par FREMYCOMPANY MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ?MBA : POURQUOI FAIRE ET COMMENT LE CHOISIR ? par ROMELARD Fabrice
Formation initiale Durant la formation, le découpage classique est le suivant (je donnerai les équivalences Suisse lorsque je les connaîtrais) : Ecole primaire jusqu'au Collège : Formation générale permettant d'obtenir les méthodes...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice Y'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENTY'A DES ERREURS QUI PEUVENT RENDRE LE DéVELOPPEUR VIOLENT par Aleks
Quand on a ce genre d'erreur sans log :
Et bas on a juste envie de choper le gas de Microsoft qu'a développé ça et lui foutre des baffes de Coboye ! ...
Cliquez pour lire la suite de l'article par Aleks
Logiciels
Academy System (17.2.1.0)ACADEMY SYSTEM (17.2.1.0)Logiciel de gestion des établissements.
- élèves/étudiants (inscription, dossier, absence...)
-... Cliquez pour télécharger Academy System Easy-Planning (1.0.0.1)EASY-PLANNING (1.0.0.1)Basé sur les mêmes principes que MyPlanning, Easy-Planning permet de créer des plannings sous la ... Cliquez pour télécharger Easy-Planning COLLECTOR PLUS (3.00B)COLLECTOR PLUS (3.00B)COLLECTOR PLUS version 3.00B est un logiciel utilisant une base de données alimentée par :
- L... Cliquez pour télécharger COLLECTOR PLUS PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO (V7.4)PONAMEDIA TV DEVIENS HELLLOOO FLASH
LA TV SUR VOTRE ORDINATEUR.
Toute une plateforme Multi... Cliquez pour télécharger PONAMEDIA PREMIUM - HELLLOOO FLASH DEMO LettresFaciles 2011 (8.0.0.1)LETTRESFACILES 2011 (8.0.0.1)LettresFaciles est un logiciel facilitant la création et la rédaction de lettres types.
Son inte... Cliquez pour télécharger LettresFaciles 2011
|