IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

C# Discussion :

Valider les données winForm


Sujet :

C#

  1. #1
    Membre habitué
    Inscrit en
    Août 2008
    Messages
    1 596
    Détails du profil
    Informations forums :
    Inscription : Août 2008
    Messages : 1 596
    Points : 175
    Points
    175
    Par défaut Valider les données winForm
    Bonjour, comment puis je valider les données d'un winForm "Les textbox", existe t'il des controles comme le range validator au niveau winForm ?

  2. #2
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Points : 39 749
    Points
    39 749
    Par défaut
    non, mais tu peux utiliser l'évènement Validating pour valider la saisie, et le composant ErrorProvider pour indiquer visuellement l'erreur

  3. #3
    Membre éclairé
    Avatar de shwin
    Profil pro
    Inscrit en
    Novembre 2003
    Messages
    568
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Novembre 2003
    Messages : 568
    Points : 777
    Points
    777
    Par défaut
    Voila une bien bonne question. Si tu est bindé à un object, je te dirait dy aller avec un IDataErrorInfo et d'utiliser l'application block de microsoft pour la validation.

    Sinon, le validating fait la job mais un peu plus broche a foin.
    Remoting Context Matters
    Everything in this chapter is 100 percent undocumented. Reliance on these techniques is not supported by either Microsoft, the publisher, or the author of this book. Use at you own risk! If your computer won't work afterwards, your toaster blows up or your car doesn't start, I assume no liability whatsoever: You're now about to enter the uncharted territories of .NET and you do so on your own risk. I can only provide some guidance

  4. #4
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par Msysteme Voir le message
    Bonjour, comment puis je valider les données d'un winForm "Les textbox", existe t'il des controles comme le range validator au niveau winForm ?
    Bonjour,

    J'ai crée hier un UserControl (textbox et son label) qui valide automatiquement les données saisies, il suffit de fixer ses propriétés dans VS.

    Pour l'instant il teste que les valeur numériques et les textes.

    Si t'es intéressé je peux te l'envoyer par MP, je ne sais pas ou le mettre sur internet.

  5. #5
    Membre habitué
    Inscrit en
    Août 2008
    Messages
    1 596
    Détails du profil
    Informations forums :
    Inscription : Août 2008
    Messages : 1 596
    Points : 175
    Points
    175
    Par défaut
    ok tu me l'envoie

  6. #6
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par Msysteme Voir le message
    ok tu me l'envoie
    Impossible par MP y a pas de support de Pièces-jointes. Donne moi ton mail.

  7. #7
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Points : 39 749
    Points
    39 749
    Par défaut
    tu veux pas le poster dans le forum plutôt ? histoire que tout le monde en profite

  8. #8
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par tomlev Voir le message
    tu veux pas le poster dans le forum plutôt ? histoire que tout le monde en profite
    J'aimerai bien mais ou? on peux pas mettre des fichiers directement.

    C'est une DLL( enfin deux).

    Pfff c'été juste un peux en bas.

    La voici .


    Explication :

    La DLL IsNumeric sert seulement à verifier si une expression est numerique ou pas, j'ai utilisé IsNumeric du VB qui n'existe pas en c#(je voulais juste ne pas me prendre la tête fallait faire vite, je lance pas le débat sur ça )

    La Dll DataValidator(mouaa le nom ) est un TextBox avec son Label, faut changer les propriétés dans Divers du Designer VS.

    TypeOfInput: Int pour numerique, Text pour texte.

    GetContent() et SetContent() pour les valeurs du textBox.

    ErrorMessage : le texte d'erreur à afficher dans le cas d'une saisie erronée.

    IsValid() : retourn True si Ok, false si non, pratique pour tester un groupe de TextBox.

    BorderColorIfError : la couleur de la bordure de la TextBox en cas d'erreur, le rouge est nickel.

    OriginalContent : le texte du label.
    UseValidator : False pour désactiver la validation de données. true si non.


    J'ai pas eu le temps de tout tester mais ça doit marcher, je l'ai fait à l'arrache.

    Bon dev.
    Dernière modification par Invité ; 25/03/2009 à 16h03.

  9. #9
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Points : 39 749
    Points
    39 749
    Par défaut
    Citation Envoyé par benqezza Voir le message
    La DLL IsNumeric sert seulement à verifier si une expression est numerique ou pas, j'ai utilisé IsNumeric du VB qui n'existe pas en c#(je voulais juste ne pas me prendre la tête fallait faire vite, je lance pas le débat sur ça )
    Pas besoin de créer une DLL pour ça, il suffit de référencer dans ton projet C# l'assembly Microsoft.VisualBasic.dll, et d'utiliser la méthode Microsoft.VisualBasic.Information.IsNumeric

  10. #10
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par tomlev Voir le message
    Pas besoin de créer une DLL pour ça, il suffit de référencer dans ton projet C# l'assembly Microsoft.VisualBasic.dll, et d'utiliser la méthode Microsoft.VisualBasic.Information.IsNumeric
    J'ai beau essayé mais ça marche pas.

    Peut être mon VS2008 déconne.

  11. #11
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Points : 39 749
    Points
    39 749
    Par défaut
    Citation Envoyé par benqezza Voir le message
    J'ai beau essayé mais ça marche pas.

    Peut être mon VS2008 déconne.
    bizarre, je le fais souvent pourtant...
    tu as fait quoi exactement ?

  12. #12
    Invité
    Invité(e)
    Par défaut
    Citation Envoyé par tomlev Voir le message
    bizarre, je le fais souvent pourtant...
    tu as fait quoi exactement ?
    bein ajouté au référence la dll Microsoft.VisualBasic

    Avec ou sans le Using Microsoft.VisualBasic

    dans le code :

    Microsoft.VisualBasic......rien

    VisualBasic...rien

    Informations...rien

    IsNumeric...toujours rien.

    J'ai fait toutes les manipulations possible...rien.

    J'ai donc fini par me créer une petite DLL rien que pour ça.

  13. #13
    Rédacteur/Modérateur


    Homme Profil pro
    Développeur .NET
    Inscrit en
    Février 2004
    Messages
    19 875
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2004
    Messages : 19 875
    Points : 39 749
    Points
    39 749
    Par défaut
    bizarre... chez moi ça marche nickel

  14. #14
    Membre émérite

    Homme Profil pro
    Développeur informatique
    Inscrit en
    Novembre 2007
    Messages
    3 387
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Novembre 2007
    Messages : 3 387
    Points : 2 999
    Points
    2 999
    Par défaut
    Pour tester le ErrorProvider, j'avais codé le petit exemple suivant, basé sur l'utilisation des expressions régulières. Si ça peut t'être utile, le voilà:

    Le designer:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
     
        partial class Form1
        {
            /// <summary>
            /// Variable nécessaire au concepteur.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
     
            /// <summary>
            /// Nettoyage des ressources utilisées.
            /// </summary>
            /// <param name="disposing">true si les ressources managées doivent être supprimées*; sinon, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
     
            #region Code généré par le Concepteur Windows Form
     
            /// <summary>
            /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
            /// le contenu de cette méthode avec l'éditeur de code.
            /// </summary>
            private void InitializeComponent()
            {
                this.components = new System.ComponentModel.Container();
                this.textBox1 = new System.Windows.Forms.TextBox();
                this.textBox2 = new System.Windows.Forms.TextBox();
                this.textBox3 = new System.Windows.Forms.TextBox();
                this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components);
                this.label1 = new System.Windows.Forms.Label();
                this.label2 = new System.Windows.Forms.Label();
                this.label3 = new System.Windows.Forms.Label();
                this.button1 = new System.Windows.Forms.Button();
                ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit();
                this.SuspendLayout();
                // 
                // textBox1
                // 
                this.textBox1.Location = new System.Drawing.Point(12, 36);
                this.textBox1.Name = "textBox1";
                this.textBox1.Size = new System.Drawing.Size(246, 20);
                this.textBox1.TabIndex = 0;
                this.textBox1.Tag = "^\\d+$";
                this.textBox1.Text = "1";
                this.textBox1.Validating += new System.ComponentModel.CancelEventHandler(this.InputValidating);
                // 
                // textBox2
                // 
                this.textBox2.Location = new System.Drawing.Point(12, 89);
                this.textBox2.Name = "textBox2";
                this.textBox2.Size = new System.Drawing.Size(246, 20);
                this.textBox2.TabIndex = 1;
                this.textBox2.Tag = "^\\W+$";
                this.textBox2.Validating += new System.ComponentModel.CancelEventHandler(this.InputValidating);
                // 
                // textBox3
                // 
                this.textBox3.Location = new System.Drawing.Point(12, 142);
                this.textBox3.Name = "textBox3";
                this.textBox3.Size = new System.Drawing.Size(246, 20);
                this.textBox3.TabIndex = 2;
                this.textBox3.Tag = "^[a-z]+$";
                this.textBox3.Validating += new System.ComponentModel.CancelEventHandler(this.InputValidating);
                // 
                // errorProvider1
                // 
                this.errorProvider1.ContainerControl = this;
                // 
                // label1
                // 
                this.label1.AutoSize = true;
                this.label1.Location = new System.Drawing.Point(13, 20);
                this.label1.Name = "label1";
                this.label1.Size = new System.Drawing.Size(42, 13);
                this.label1.TabIndex = 3;
                this.label1.Text = "Chiffres";
                // 
                // label2
                // 
                this.label2.AutoSize = true;
                this.label2.Location = new System.Drawing.Point(13, 73);
                this.label2.Name = "label2";
                this.label2.Size = new System.Drawing.Size(99, 13);
                this.label2.TabIndex = 3;
                this.label2.Text = "Ni chiffres, ni lettres";
                // 
                // label3
                // 
                this.label3.AutoSize = true;
                this.label3.Location = new System.Drawing.Point(12, 126);
                this.label3.Name = "label3";
                this.label3.Size = new System.Drawing.Size(39, 13);
                this.label3.TabIndex = 3;
                this.label3.Text = "Lettres";
                // 
                // button1
                // 
                this.button1.Enabled = false;
                this.button1.Location = new System.Drawing.Point(183, 231);
                this.button1.Name = "button1";
                this.button1.Size = new System.Drawing.Size(75, 23);
                this.button1.TabIndex = 4;
                this.button1.Text = "button1";
                this.button1.UseVisualStyleBackColor = true;
                // 
                // Form1
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(292, 266);
                this.Controls.Add(this.button1);
                this.Controls.Add(this.label3);
                this.Controls.Add(this.label2);
                this.Controls.Add(this.label1);
                this.Controls.Add(this.textBox3);
                this.Controls.Add(this.textBox2);
                this.Controls.Add(this.textBox1);
                this.Name = "Form1";
                this.Text = "Form1";
                this.Shown += new System.EventHandler(this.Form1_Shown);
                ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit();
                this.ResumeLayout(false);
                this.PerformLayout();
     
            }
     
            #endregion
     
            private System.Windows.Forms.TextBox textBox1;
            private System.Windows.Forms.TextBox textBox2;
            private System.Windows.Forms.TextBox textBox3;
            private System.Windows.Forms.ErrorProvider errorProvider1;
            private System.Windows.Forms.Label label3;
            private System.Windows.Forms.Label label2;
            private System.Windows.Forms.Label label1;
            private System.Windows.Forms.Button button1;
        }
    Le formulaire:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
     
    using System.ComponentModel;
    using System.Text.RegularExpressions;
    using System.Windows.Forms;
     
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
     
            System.Collections.Generic.Dictionary<string, string> tests = new System.Collections.Generic.Dictionary<string, string>()
            {
                {@"^\d+$", "Au moins un chiffre et seulement un chiffre"},
                {@"^[a-z]+$", "Au moins une lettre et seulement une lettre"},
                {@"^\W+$", "Au moins un caractère mais NI un chiffre, NI une lettre"}
            };
     
            public Form1()
            {
                InitializeComponent();
                ActiveControl = textBox1;
            }
     
            private void InputValidating(object sender, CancelEventArgs e)
            {
                TextBox textBox = sender as TextBox;
                errorProvider1.SetError(textBox,
                    Regex.IsMatch(textBox.Text, (string)textBox.Tag) ? "" : tests[(string)textBox.Tag]);
                bool invalidInput = false;
                foreach (Control ctrl in this.Controls)
                {
                    if (((ctrl is TextBox) && string.IsNullOrEmpty((ctrl as TextBox).Text)) || errorProvider1.GetError(ctrl) != "")
                    {
                        invalidInput = true;
                        break;
                    }
                }
                button1.Enabled = !invalidInput;
            }
     
            private void Form1_Shown(object sender, System.EventArgs e)
            {
                errorProvider1.BlinkStyle = ErrorBlinkStyle.NeverBlink;
                bool invalidInput = false;
                foreach (Control ctrl in this.Controls)
                {
                    if (ctrl is TextBox)
                    {
                        InputValidating(ctrl, new CancelEventArgs());
                        invalidInput = invalidInput | (errorProvider1.GetError(ctrl) != "");
                    }
                }
                button1.Enabled = !invalidInput;
                errorProvider1.BlinkStyle = ErrorBlinkStyle.BlinkIfDifferentError;
            }
     
        }
    }
    L'appel en boucle de InputValidating dans le FormShown permet de montrer tout de suite les champs à remplir avec les formats de valeurs attendues.

    Le format est utilisé dans la propriété tag de chaque textbox, ce tag permettant de retrouver la chaîne d'érreur à afficher en cas d'erreur.

    Bien sur, il faut ensuite ajuster chaque expression régulière pour les valeurs attendues.

Discussions similaires

  1. valider les données d'un formview avec un boutton
    Par cooper1990 dans le forum ASP
    Réponses: 1
    Dernier message: 10/10/2011, 10h05
  2. Impossible de valider les données
    Par tom974 dans le forum Configuration
    Réponses: 12
    Dernier message: 12/11/2009, 10h03
  3. Impossible de valider les données
    Par tom974 dans le forum SharePoint
    Réponses: 9
    Dernier message: 01/10/2009, 11h11
  4. [2.2.2] Valider les données XML par XSD
    Par Epsilon38 dans le forum BIRT
    Réponses: 3
    Dernier message: 25/03/2009, 15h52
  5. Valider les données d'un formulaire
    Par bdminc dans le forum Langage
    Réponses: 3
    Dernier message: 20/09/2007, 17h13

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo