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
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:
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
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:
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....