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 :

Fichier text et datagridview


Sujet :

VB.NET

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé Avatar de biquet
    Homme Profil pro
    Inscrit en
    Juillet 2003
    Messages
    199
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Juillet 2003
    Messages : 199
    Par défaut Fichier text et datagridview
    Bonjour,

    tout d'abord je précise que je suis débutant en vb net et que c'est la première fois que j'utilise datagridview.
    Aprés plusieurs heures de recherche je suis perdu.

    J'ai un fichier *.dat qui contient plusieurs ligne. sur chaque ligne, il y a des infos séparés par des point-virgule.

    Je voudrais afficher ces données dans un datagridview sur ma form.
    Précision chaque données entre les point-virgule = 1 colonne et cahque ligne = 1 ligne.

    par avance merci de me mettre sur le chemin

  2. #2
    Membre confirmé Avatar de biquet
    Homme Profil pro
    Inscrit en
    Juillet 2003
    Messages
    199
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Juillet 2003
    Messages : 199
    Par défaut
    bonjour,

    j'ai une solution mais je sais pas si c la meilleure
    Je lis le fichier ligne par ligne et je split la ligne à chaque ;
    Et j'ecris dans mon datagridview les valeurs voulues.

    existe t-il une solution plus rapide à votre avis?

  3. #3
    Membre très actif Avatar de oussi
    Profil pro
    Étudiant
    Inscrit en
    Octobre 2009
    Messages
    192
    Détails du profil
    Informations personnelles :
    Âge : 34
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Octobre 2009
    Messages : 192
    Par défaut
    Personnelement je l'aurai fait de la même manière

  4. #4
    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 TextFieldParser,Delimited,StreamWriter
    Bonjour biquet
    c'est bon,mais si tu veux developper une appli c'est limite.Voici plus pro.
    1/tu crees une classe avec une propriete publique qui correspond a chaque champ colonne(colonne si tu veux)
    2/tu lis ton fichier avec TextFieldParser,avec options SetDelimiters(";"),il est fait expres pour ce boulot.
    3/dans ton appli tu crees une liste de ta classe qui va stocker chaque instance de ta classe (correspond à une ligne)
    4/tu fais simplement datagridview.datasource=maliste et hop ils sont dedans.
    5/l'avantage de la liste : toute modif dans le datagridview est reporte dans la liste.
    6/tu enregistre ta liste dans le fichier .dat.
    voici un exemple avec un fichier.dat
    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
     
    'la classe qui correspond à ton fichier .dat
    'à modifier :une prop=>colonne.
    Public Class Fiche_Du_Livre
     
        Private m_Genre As String
        Public Property Genre() As String
            Get
                Return m_Genre
            End Get
            Set(ByVal value As String)
                m_Genre = value
            End Set
        End Property
     
        Private m_Auteur As String
        Public Property Auteur() As String
            Get
                Return m_Auteur
            End Get
            Set(ByVal value As String)
                m_Auteur = value
            End Set
        End Property
        Private m_Titre As String
        Public Property Titre() As String
            Get
                Return m_Titre
            End Get
            Set(ByVal value As String)
                m_Titre = value
            End Set
        End Property
        Private m_ID As Integer
        Public Property ID() As Integer
            Get
                Return m_ID
            End Get
            Set(ByVal value As Integer)
                m_ID = value
            End Set
        End Property
        Private m_Disponibilite As String
        Public Property Disponibilite() As String
            Get
                Return m_Disponibilite
            End Get
            Set(ByVal value As String)
                m_Disponibilite = value
            End Set
        End Property
     
    End Class
    'le form du projet
    Imports System
    Imports System.IO
    Imports System.Windows
    Imports System.Collections.Generic
    Public Class Form1
        Private objFiche As Fiche_Du_Livre
        Private listeLivre As List(Of Fiche_Du_Livre) = New List(Of Fiche_Du_Livre)
        Private Sub btnOuvrirFichier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOuvrirFichier.Click
            Dim fichierChemin As String = ""
            Me.OpenFileDialog1.Filter = "Fichier Texte(*.dat)|*.dat"
            If Me.OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                fichierChemin = Me.OpenFileDialog1.FileName
                If Len(fichierChemin) = 0 Then
                    MessageBox.Show("erreur fichier...")
                    Exit Sub
                Else
                    Call LitFichier(fichierChemin)
                    DataGridView1.DataSource = listeLivre
     
                End If
            End If
        End Sub
        'Lit le Fichier
        Private Sub LitFichier(ByVal cheminfichier As String)
            Using monReader As New  _
            Microsoft.VisualBasic.FileIO.TextFieldParser(cheminfichier)
                monReader.TextFieldType = FileIO.FieldType.Delimited
     
                monReader.SetDelimiters(";")
                Dim ligneCourante As String()
                Dim afficheLigCourante As String = ""
                Dim numChamp As Integer = 1
                While Not monReader.EndOfData
                    Try
                        ligneCourante = monReader.ReadFields()
                        Dim champCourant As String = String.Empty
                        objFiche = New Fiche_Du_Livre
                        numChamp = 1
                        For Each champCourant In ligneCourante
                            Select Case numChamp
                                Case 1
                                    objFiche.Genre = CType(champCourant, String)
                                Case 2
                                    objFiche.Auteur = CType(champCourant, String)
                                Case 3
                                    objFiche.Titre = CType(champCourant, String)
                                Case 4
                                    objFiche.ID = Integer.Parse(champCourant)
                                Case 5
                                    objFiche.Disponibilite = Integer.Parse(champCourant)
                            End Select
                            'champ suivant
                            numChamp = numChamp + 1
                            afficheLigCourante = afficheLigCourante & champCourant
                        Next
     
                        Call stockeFicheDuLivre(objFiche)
                        'ligne suivante
                        MessageBox.Show(afficheLigCourante)
                        afficheLigCourante = ""
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MsgBox("Ligne " & ex.Message & _
                        "non valide,sera saute....")
                    End Try
                End While
            End Using
        End Sub
        'Stocke dans liste
        Private Sub stockeFicheDuLivre(ByVal objFiche As Fiche_Du_Livre)
            listeLivre.Add(objFiche)
        End Sub
        'Enregistre le fichier
        Private Sub btnEnregFichier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnregFichier.Click
            Dim fichierChemin As String = ""
            Me.SaveFileDialog1.Filter = "Fichier Texte(*.dat)|*.dat"
            If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                fichierChemin = Me.SaveFileDialog1.FileName
                If Len(fichierChemin) = 0 Then
                    MessageBox.Show("erreur fichier...")
                    Exit Sub
                Else
                    Call EcritFichier(fichierChemin)
     
                End If
            End If
        End Sub
     
        Private Sub EcritFichier(ByVal cheminfichier As String)
            Dim MonWriter As System.IO.StreamWriter = New System.IO.StreamWriter(cheminfichier, False)
            Dim strLigne As String = ""
            Dim sep As String = ";"
            Try
                For Each objLivre In listeLivre
                    strLigne = objLivre.Genre & sep & objLivre.Auteur & objLivre.Titre & sep & objLivre.ID.ToString & sep & objLivre.Titre
                    MonWriter.WriteLine(strLigne)
                Next
                MonWriter.Close()
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                MsgBox("Ligne " & ex.Message & _
                "non valide,sera saute....")
            End Try
        End Sub
     
     
    End Class
    pj:fichier rar de l'exemple pour vs2008
    bon code

  5. #5
    Membre confirmé Avatar de biquet
    Homme Profil pro
    Inscrit en
    Juillet 2003
    Messages
    199
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Juillet 2003
    Messages : 199
    Par défaut
    merci pour cette réponse très pro
    Il faut que je comprenne et je l'implémenterai dans mon prog.

    Peux t'on par ta réponse jouer sur des filtres afin de n'afficher que certaines choses.
    En fait mon fichier . dat reprend tout un stock (une centaine de ligne max) mais je voudrais afficher que ce qui vient d'un fournisseur ou d'un autre, ou certain conditionnement (voir les deux cumulés en même temps).

    un peu comme le système de filtre d'excel qui permet de sélectionner tout ou un paramètres de la colonne et sur plusieurs colonnes?

    j'espère avoir été clair.

    bien à vous

  6. #6
    Membre confirmé Avatar de biquet
    Homme Profil pro
    Inscrit en
    Juillet 2003
    Messages
    199
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : France, Nord (Nord Pas de Calais)

    Informations forums :
    Inscription : Juillet 2003
    Messages : 199
    Par défaut
    Merci MABROUKI
    ton aide m'a permis de gagner du temps et d'être plus pro.

    Tous fonctionne correctement.

    Reste ma question du filtre juste au dessus

    bonne journée

  7. #7
    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 Fichier,filtre, datatable
    bonjour biquet
    En fait si tu veux des fonctionnalites avances de tri et filtrage,il faut changer d'arme et au lieu d'utiliser une liste ,on va utiliser un datable couple à dataview.
    Voici notre precedent bout de code repris en utilisant ces 2 outils legerement modifie.
    Note aussi l'utilisation de la variable Systeme.Type pour ajouter les colonnes de la table et ses intitules au lieu de les coder en dur.
    code revu :
    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
     
     
    'pour la syntaxe precise de DataView.RowFilter avec ses variantes
    'voir doc MSDN
    Imports System
    Imports System.IO
    Imports System.Windows
    Imports System.Data
    Public Class frmTriFiltre
        Private objFiche As Fiche_Du_Livre
        'declare un datable au lieu d'une liste
        Private dt As DataTable = New DataTable("maTable")
     
        Private Sub btnOuvrirFichier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOuvrirFichier.Click
            Dim fichierChemin As String = ""
            Me.OpenFileDialog1.Filter = "Fichier Texte(*.dat)|*.dat"
            If Me.OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                fichierChemin = Me.OpenFileDialog1.FileName
                If Len(fichierChemin) = 0 Then
                    MessageBox.Show("erreur fichier...")
                    Exit Sub
                Else
                    'cree un datatable
                    Call CreeDataTableFicheDuLivre()
                    Call LitFichier(fichierChemin)
                    'lie combobox à colonne Auteur
                    Me.cboFilterAuteur.DataSource = dt
                    Me.cboFilterAuteur.DisplayMember = dt.Columns(1).ColumnName
                    Me.cboFilterAuteur.ValueMember = dt.Columns(1).ColumnName
                    Me.DataGridView1.DataSource = dt
                End If
            End If
        End Sub
        'Lit le Fichier
        Private Sub LitFichier(ByVal cheminfichier As String)
            Using monReader As New  _
            Microsoft.VisualBasic.FileIO.TextFieldParser(cheminfichier)
                monReader.TextFieldType = FileIO.FieldType.Delimited
     
                monReader.SetDelimiters(";")
                Dim ligneCourante As String()
                Dim afficheLigCourante As String = ""
                Dim numChamp As Integer = 1
                Dim dr As DataRow
                While Not monReader.EndOfData
                    Try
                        ligneCourante = monReader.ReadFields()
                        Dim champCourant As String = String.Empty
                        dr = dt.NewRow
                        'objFiche = New Fiche_Du_Livre
                        numChamp = 1
                        For Each champCourant In ligneCourante
                            Select Case numChamp
                                Case 1
                                    dr(0) = CType(champCourant, String)
                                Case 2
                                    dr(1) = CType(champCourant, String)
                                Case 3
                                    dr(2) = CType(champCourant, String)
                                Case 4
                                    dr(3) = Integer.Parse(champCourant)
                                Case 5
                                    dr(4) = Integer.Parse(champCourant)
                            End Select
                            'champ suivant
                            numChamp = numChamp + 1
                            afficheLigCourante = afficheLigCourante & champCourant
                        Next
                        dt.Rows.Add(dr)
                        'ligne suivante
                        MessageBox.Show(afficheLigCourante)
                        afficheLigCourante = ""
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MsgBox("Ligne " & ex.Message & _
                        "non valide,sera saute....")
                    End Try
                End While
            End Using
        End Sub
        'Cree un DataTable au lieu d'une Liste
        Private Sub CreeDataTableFicheDuLivre()
            'On definit  colonnes DataTable à partir des Prop de la classe
            Dim col As DataColumn = New DataColumn
            Dim monType As Type = GetType(Fiche_Du_Livre)
            For Each prop In monType.GetProperties
                col = New DataColumn
                col.ColumnName = prop.Name
                col.Caption = prop.Name
                col.DataType = prop.PropertyType
                dt.Columns.Add(col)
            Next
        End Sub
        'Enregistre le fichier
        Private Sub btnEnregFichier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnregFichier.Click
            Dim fichierChemin As String = ""
            Me.SaveFileDialog1.Filter = "Fichier Texte(*.dat)|*.dat"
            If Me.SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
                fichierChemin = Me.SaveFileDialog1.FileName
                If Len(fichierChemin) = 0 Then
                    MessageBox.Show("erreur fichier...")
                    Exit Sub
                Else
                    Call EcritFichier(fichierChemin)
     
                End If
            End If
        End Sub
     
     
        Private Sub EcritFichier(ByVal cheminfichier As String)
            Dim MonWriter As System.IO.StreamWriter = New System.IO.StreamWriter(cheminfichier, False)
            Dim strLigne As String = ""
            Dim sep As String = ";"
            Try
                For Each objLivre As DataRow In dt.Rows
                    strLigne = objLivre(0) & sep & objLivre(1) & sep & objLivre(2) & sep & objLivre(3).ToString & sep & objLivre(4).ToString
                    MonWriter.WriteLine(strLigne)
                Next
                MonWriter.Close()
            Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                MsgBox("Ligne " & ex.Message & _
                "non valide,sera saute....")
            End Try
        End Sub
     
        Private Sub cboFilterAuteur_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboFilterAuteur.SelectedIndexChanged
            'syntaxe filtre :filtreView.RowFilter = "NomColonne = 'valeur'"
            ' Cree une vue filtre Colonne Auteur =Castro
            Dim filtreView As DataView = New DataView(dt)
            Dim colFiltre = dt.Columns.Item(1).ColumnName
            filtreView.RowFilter = colFiltre & "=" & "'" & cboFilterAuteur.SelectedValue.ToString & "'"
     
            DataGridView1.DataSource = filtreView
            DataGridView1.Update()
        End Sub
     
        Private Sub btnTrier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTrier.Click
            ' Cree une vue trie( ASC ou DESC)
            Dim triView As DataView = New DataView(dt)
            triView.Sort = "Auteur ASC"
            ' Lie DataGridView  à triView
            DataGridView1.DataSource = triView
        End Sub
    End Class
    bon code....

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

Discussions similaires

  1. Fichier texte via datagridview
    Par DD-78 dans le forum VB.NET
    Réponses: 1
    Dernier message: 01/12/2013, 09h41
  2. Réponses: 4
    Dernier message: 06/09/2010, 20h08
  3. [VB6] Ecrire/Modifier/Effacer ds un fichier text-4 Chs/Lg
    Par Jonathan_Korvitch dans le forum VB 6 et antérieur
    Réponses: 18
    Dernier message: 24/12/2002, 18h54
  4. Importer des fichiers textes délimités
    Par Invité dans le forum Outils
    Réponses: 2
    Dernier message: 23/09/2002, 13h56
  5. Instruction pour créer un fichier text ???
    Par Soulsurfer dans le forum Langage
    Réponses: 2
    Dernier message: 06/08/2002, 11h17

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