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

VB.NET Discussion :

[VB]Aide lire fichier


Sujet :

VB.NET

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Homme Profil pro
    Inscrit en
    Février 2009
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Février 2009
    Messages : 12
    Par défaut [VB]Aide lire fichier
    Bonsoir je vous sollicite pour un exercice de visual basic.Je viens de lire le tuto sur ce language de programmation et je me suis mis à chercher des exercices.Je suis tombé sur celui-là: http://mrproof.blogspot.com/2010/09/tp [...] ammation.html
    Mon problème se situe au niveau du contrôle 4 pour parcourir le fichier . dat afin de l'afficher dans les textbox et combobox .
    Alors j'aimerais savoir comment on peut récupérer dans un fichier .dat qui ressemble à ça:
    Resultat.dat
    22 08 1 23,76
    33 08 1 35,64
    44 08 1 47,52
    55 08 1 59,4
    les valeurs pour les envoyer dans différents textbox ou combobox.
    Exemple:
    22 dans textbox1
    08 dans combobox1
    1 dans combobox2
    23,76 dans textbox2
    Et si on appui sur un bouton les valeurs sont celle de la ligne suivante.
    J'espère avoir été clair.Merci de votre aide car je débute et la je cherche depuis 2 jours et je trouve pas de solution.

    Voila ou j'en suis dans mon codej'espère pas trop choquer les pros de la programmation)

    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
    Imports System.IO
    Public Class Form1
        Const PATHFICHIER As String = "Resultat.txt"
        Dim PATHRESULTAT As String = "Resultat.Dat"
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Me.Label5.Visible = False
            Me.Label5.ForeColor = Color.Red
        End Sub
     
        Private Sub QuitterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuitterToolStripMenuItem.Click
            If MsgBox("Souhaitez-vous vraiment quitter ce programme ?", 36, "Quitter") = MsgBoxResult.Yes Then
                End
            End If
        End Sub
     
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Me.TextBox1.Text = ""
            Me.TextBox2.Text = ""
            Me.ComboBox1.SelectedIndex = -1
            Me.ComboBox2.SelectedIndex = -1
        End Sub
        Function Verification() As Boolean
            Dim Bon As Boolean = True
            If Me.TextBox1.Text Is Nothing Or Not IsNumeric(Me.TextBox1.Text) Then
                Bon = False
            End If
            Return Bon
        End Function
        Function Calcul(ByVal TextBox1 As Double, ByVal ComboBox1 As Double, ByVal ComboBox2 As Double) As Double
            Dim D As Double = TextBox1
            Dim z As Integer = 0
            While z <> ComboBox2
                D = D * (1 + ComboBox1 / 100)
                z = z + 1
            End While
            Return D
        End Function
     
        Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
            If Verification() Then
                Me.TextBox2.Text = Calcul(Me.TextBox1.Text, Me.ComboBox1.Text, Me.ComboBox2.Text)
            Else
                Me.Label5.Visible = True
            End If
        End Sub
     
        Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            File.WriteAllText(PATHFICHIER, "Capital Initial :" & Me.TextBox1.Text & vbNewLine & "Taux :" & Me.ComboBox1.Text & "%" & vbNewLine & "Nombre d'années :" & Me.ComboBox2.Text & vbNewLine & "Capital final:" & Me.TextBox2.Text)
        End Sub
     
        Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
            File.AppendAllText(PATHRESULTAT, Me.TextBox1.Text & " " & Me.ComboBox1.Text & " " & Me.ComboBox2.Text & " " & Me.TextBox2.Text & vbNewLine)
        End Sub
     
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
           File.ReadAllText (Resultat.Dat,Integer) = ( Me.TextBox1.Text , Me.ComboBox1.Text , Me.ComboBox2.Text , Me.TextBox2.Text ) 
            Do Until EOF(f)
           ???????????????
    ??????????????????????????????
        End Sub
    End Class

  2. #2
    Membre expérimenté Avatar de anonymousse
    Profil pro
    Inscrit en
    Février 2011
    Messages
    130
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2011
    Messages : 130
    Par défaut
    bonjour netfoot,

    en premier lieu je t'invite à parcourir les nombreux cours existants, tu gagneras beaucoup de temps, exemple : http://msdn.microsoft.com/en-us/library/3z2ck8eh.aspx

    en deuxième temps tu y trouveras quelques règle de programmation qui éclaircirons tes codes et en particulier je t'invites fortement à les commenter car après plusieurs centaines de lignes de code tu n'y comprendra plus rien (et les membres du forum ne pourrons te répondre rapidement).

    cela étant dit tu as plusieurs anomalies que tu pourra corriger en consultant les méthodes file http://msdn.microsoft.com/en-us/library/3z2ck8eh.aspx (puisque tu travailles avec, fais attention tout de même si tes données enflent il faudra peut-être mieux envisager des solution base de données, Datagridview et autres.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
           File.ReadAllText (Resultat.Dat,Integer) = ( Me.TextBox1.Text , Me.ComboBox1.Text , Me.ComboBox2.Text , Me.TextBox2.Text ) 
            Do Until EOF(f)
           ???????????????
    ??????????????????????????????
        End Sub
    si tu utilises ReadAllText comme son nom "l'indique" tu lis la totalité de ton fichier, il faut à mon avis utiliser ReadLines pour obtenir une collection de lignes et caster les data pour les répartir dans tes contrôles TextBox et Combobox.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    For Each line As String In File.ReadLines("Resultat.Dat")
        ...
    Next line
    bon code ...

  3. #3
    Membre extrêmement actif
    Inscrit en
    Avril 2008
    Messages
    2 573
    Détails du profil
    Informations personnelles :
    Âge : 65

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 573
    Par défaut lire un fichier texte sdf,fixedwidth
    Bonjour NetFoot
    voici comment lire un fichier "fixedwidth" appele aussi Format SDF c'est à dire delimited par des espaces et à -largeur de colonne fixe.
    c'est le fichier le plus enquiquinant parce il est facile de le lire mais sa reecriture peut poser des problemes avec les nombres et les strings car il faut les "trimmer" et les "justifier".
    Voici ton code revu avec un datatable , TextFieldParser pour lire et StreamWriter pour ecrire.
    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
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
     
     
     
    'AJOUTER 3 CONTROLES:
    '- DataGridView (pour voir l'ensemble des enregistrements)
    '- BindingSource1(pour lier les controles au navigateur)
    '- BindingNavigator1 (pour naviguer dans les TextBox avec un Click)
    'NB: les ComboBox sont inutiles
    'NB: btnAppend est supprime (a remplacer par un  DataGridView)
    Imports System.IO
    Imports System.Data
    Imports System.Text
    Imports System.Reflection
     
    Public Class Form1
        'Enum definit tes largeurs de colonne dans l'ordre d'apparition(en nombre de caracteres)
        Public Enum largCol
            col1 = 3 '=largeur colon capital initial+espace
            col2 = 3 '=colonne NbreAnnees+espace
            col3 = 2 '=colonne Taux+espace
            col4 = 5 '=colonne CapitalFinal+espace
        End Enum
        Private PATHFICHIER As String = Directory.GetCurrentDirectory & "\Resultat.txt"
        Private PATHRESULTAT As String = Directory.GetCurrentDirectory & "\datResultat.txt"
        Dim dtCapital As DataTable
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Me.Label5.Visible = False
            Me.Label5.ForeColor = Color.Red
     
            'RAZ DES TEXTBOX
            Me.txtCapitalInitial.Text = ""
            Me.txtNbreAnnees.Text = ""
            Me.txtTaux.Text = ""
            Me.txtCapitalFinal.Text = ""
     
            'INIT UN DataTable dtCapital
            dtCapital = New DataTable
     
            'ET CREE LES 4 COLONNES DANS L'ORDRE
            Dim colType As DataColumn = New DataColumn
            colType = dtCapital.Columns.Add("CapitalInitial", GetType(Double))
            colType.DefaultValue = 0.0
            colType = dtCapital.Columns.Add("NbreAnnees", GetType(Integer))
            colType.DefaultValue = 0
            colType = dtCapital.Columns.Add("Taux", GetType(Integer))
            colType.DefaultValue = 0
            colType = dtCapital.Columns.Add("CapitalFinal", GetType(Double))
            colType.DefaultValue = 0
        End Sub
        Private Sub QuitterToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuitterToolStripMenuItem.Click
            If MsgBox("Souhaitez-vous vraiment quitter ce programme ?", 36, "Quitter") = MsgBoxResult.Yes Then
                End
            End If
     
        End Sub
        '-----------------Lecture utilise TextFieldParser---------------------
        Private Sub btnRAZ_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRAZ.Click
            Me.txtCapitalInitial.Text = ""
            Me.txtNbreAnnees.Text = ""
            Me.txtTaux.Text = ""
            Me.txtCapitalFinal.Text = ""
     
        End Sub
        '-----------------Lecture utilise TextFieldParser---------------------
        Private Sub btnReadAll_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadAll.Click
            If Not File.Exists(PATHFICHIER) Then
                MessageBox.Show(PATHFICHIER & " n'existe pas...")
                Return
            End If
            'ligne texte
            Dim ligneLue() As String
            Using monReader As New  _
            Microsoft.VisualBasic.FileIO.TextFieldParser(PATHFICHIER)
                'Fichier Fixe (SDF)
                monReader.TextFieldType = FileIO.FieldType.FixedWidth
                'Largeur colonne
                monReader.SetFieldWidths(largCol.col1, largCol.col2, largCol.col3, largCol.col4)
                'ligne DataTable
                Dim dr As DataRow
                While Not monReader.EndOfData
                    Try
                        ligneLue = monReader.ReadFields()
                        dr = dtCapital.NewRow
                        dr.ItemArray = ligneLue
                        dtCapital.Rows.Add(dr)
                    Catch ex As  _
                    Microsoft.VisualBasic.FileIO.MalformedLineException
                        MsgBox("Ligne Invalide " & ex.Message & _
                        "sera sautee...")
                    End Try
                    'ligne suivante
                End While
                MessageBox.Show("Fin de fichier Atteinte...")
                monReader.Close()
            End Using
            Me.BindingSource1.DataSource = dtCapital
            Me.BindingSource1.DataMember = dtCapital.TableName
            Me.BindingNavigator1.BindingSource = Me.BindingSource1
     
     
            Me.DataGridView1.DataSource = Me.BindingSource1
            'Lie les controles a BindingSource1
            Me.txtCapitalInitial.DataBindings.Add(New Binding("Text", Me.BindingSource1, dtCapital.Columns(0).ColumnName, True))
            Me.txtNbreAnnees.DataBindings.Add(New Binding("Text", Me.BindingSource1, dtCapital.Columns(1).ColumnName, True))
            Me.txtTaux.DataBindings.Add(New Binding("Text", Me.BindingSource1, dtCapital.Columns(2).ColumnName, True))
            Me.txtCapitalFinal.DataBindings.Add(New Binding("Text", Me.BindingSource1, dtCapital.Columns(3).ColumnName, True))
     
            'Desactive
            btnReadAll.Enabled = False
        End Sub
        '-----------------Ecriture utilise StreamWriter---------------------
        Private Sub btnWriteALL_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWriteALL.Click
            Using MonWriter As New StreamWriter(PATHRESULTAT, False)
                Try
     
                    Dim strLigne As String = ""
                    Dim Espace = " "
                    For Each dr As DataRow In dtCapital.Rows
                        For Each dc As DataColumn In dtCapital.Columns
                            strLigne = strLigne & dr(dc) & Espace
                        Next
                        'strLigne = strLigne & Strings.RSet(DR.Item(0).ToString, 2) & Espace & Strings.RSet(DR.Item(1).ToString, 2) & Espace & Strings.RSet(DR.Item(2).ToString, 1) & Espace & Strings.RSet(DR.Item(3).ToString, 5)
                        MonWriter.WriteLine(strLigne)
                        ' ligne suivante
                        strLigne = ""
                    Next
                Catch ex As Exception
                    MessageBox.Show("Erreur d'ecriture fichier " & ex.Message)
                End Try
                MessageBox.Show("Fichier Sortie Resultat.dat...")
                MonWriter.Close()
            End Using
            '----------------------NOUVELLE SESSION RESET DES CONTROLES-------------
            'VIDE LA TABLE 
            dtCapital.Clear()
            'SUPPRIME LES LIAISONS DES CONTROLES TEXTBOX
            Me.txtCapitalInitial.DataBindings.Clear()
            Me.txtNbreAnnees.DataBindings.Clear()
            Me.txtTaux.DataBindings.Clear()
            Me.txtCapitalFinal.DataBindings.Clear()
            Me.DataGridView1.Refresh()
            'ACTIVE btnReadAll
            btnReadAll.Enabled = True
        End Sub
     
        Private Sub btnCalcul_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalcul.Click
            If Verification() Then
                Try
                    Dim valCalc As Double = Calcul(Double.Parse(Me.txtCapitalInitial.Text), Double.Parse(Me.txtTaux.Text), Double.Parse(Me.txtNbreAnnees.Text))
                    Me.txtCapitalFinal.Text = Math.Round(valCalc, 2).ToString
                Catch ex As Exception
                    MessageBox.Show("erreur donnee..." & ex.ToString)
                End Try
            Else
                Me.Label5.Visible = True
            End If
        End Sub
     
        Function Verification() As Boolean
            Dim Bon As Boolean = True
            If Me.txtCapitalInitial.Text Is Nothing Or Not IsNumeric(Me.txtCapitalInitial.Text) Then
                Bon = False
            End If
            Return Bon
        End Function
        Function Calcul(ByVal VALtxtCapitalInitial As Double, ByVal VALcboTaux As Double, ByVal VALcboNbreAnnees As Double) As Double
            Dim D As Double = VALtxtCapitalInitial
            Dim z As Integer = 0
            While z <> VALcboNbreAnnees
                D = D * (1 + VALcboTaux / 100)
                z = z + 1
            End While
            Return D
        End Function
    End Class

  4. #4
    Membre averti
    Homme Profil pro
    Inscrit en
    Février 2009
    Messages
    12
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations forums :
    Inscription : Février 2009
    Messages : 12
    Par défaut
    Merci vous m'avez bien aidé.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [Débutant] aide: lire un fichier binary file (structure connue)
    Par forzacodm dans le forum VB.NET
    Réponses: 0
    Dernier message: 01/04/2013, 20h26
  2. aide creer et lire fichier config dans home/utilisateur
    Par themulot dans le forum Administration système
    Réponses: 2
    Dernier message: 28/12/2007, 12h36
  3. Aide sur fichier batch
    Par Flushovsky dans le forum Windows
    Réponses: 13
    Dernier message: 14/12/2007, 08h21
  4. m'aidé! lire fichier+comparaison+envoi courriel
    Par Rocco_Canada dans le forum Langage
    Réponses: 4
    Dernier message: 21/09/2006, 15h08

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