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
UNE JOLIE-HORLOGE ET PAS QU'UN PEU !UNE JOLIE-HORLOGE ET PAS QU'UN PEU ! par neodante
Pour les possesseurs d'iPhone, ça y est Bijin Tokei - qui se traduit littéralement en Français par " Jolie Horloge " - est arrivé et GRATUITEMENT s'il vous plaît ! Après la version Tokyo, Hokkaido, night club, racing, Gal, "pour les mademoiselles'", . voi...
Cliquez pour lire la suite de l'article par neodante TECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICESTECHDAYS PARIS 2010 : CONNECTEZ VOS DONNéES à SHAREPOINT 2010 AVEC LES BUSINESS CONNECTIVITY SERVICES par ROMELARD Fabrice
Animé par: Gaetan Bouveret et Julien Chomarat Business Connectivity Services (BCS) est dans SharePoint 2010 la version 2 de Business Data Catalog (BDC dans SharePoint 2007). Il s'agit de la solution permettant de visualiser des données provenan...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice [DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE[DIVERS] SUIVRE VOS SéRIES PRéFéRéS SUR LA TOILE par orion
Comme de nombreux geek, je suis un grand amateur de série TV et je rate régulièrement des épisodes de mes séries préférés. Une solution s'offre à vous avec ce merveilleux site : Tv Gorge - www.tvgorge.com Moteur de recherche à l'appui, vous pouvez ...
Cliquez pour lire la suite de l'article par orion TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010TECHDAYS PARIS 2010 : LA BI DANS SHAREPOINT 2010 par ROMELARD Fabrice
Animé par: Vincent Bellet et Baptiste Giraudier La BI dans SharePoint 2010, Les nouveaux services d'application dans SP2010 et SQL Server Reporting services 2008 R2. La BI dans SharePoint est généralisée pour tous afin de permettre à tous les coll...
Cliquez pour lire la suite de l'article par ROMELARD Fabrice
Logiciels
DB-MAIN (9.1.0)DB-MAIN (9.1.0)DB-MAIN is a data-modeling and data-architecture tool. It is designed to help developers and anal... Cliquez pour télécharger DB-MAIN Xilisoft DPG Convertisseur (5.1.37.0120)XILISOFT DPG CONVERTISSEUR (5.1.37.0120)Xilisoft DPG Convertisseur offre aux fans de Nintendo DS une bonne solution leur permettant de dé... Cliquez pour télécharger Xilisoft DPG Convertisseur GraphicsGale (2.01.01)GRAPHICSGALE (2.01.01)GraphicsGale est un logiciel de PixelArt avec de nombreuse fonctionnalités permettant de réalisé ... Cliquez pour télécharger GraphicsGale Architecte 3D (Platinum 2010)ARCHITECTE 3D (PLATINUM 2010)Architecte 3D Platinium vous permet de concevoir facilement les plans votre future maison, de l'é... Cliquez pour télécharger Architecte 3D TeamViewer 5 (TeamViewer 5)TEAMVIEWER 5 (TEAMVIEWER 5)Dépanner un ami,expliquer une manipulation devient un jeu d'enfant.
Prise en main d'un autre ord... Cliquez pour télécharger TeamViewer 5
|