Problème de conflit de code dans des procédures de listBox ?

Résolu
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 - 4 janv. 2012 à 11:33
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 - 7 janv. 2012 à 00:54
Bonjour,

J'ai un truc pas mal que voici en code :

Sub ListBox2_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox2.MouseDown
    MsgBox(ListBox2.Items.Count)
    If ListBox2.Items.Count < 1 Then Exit Sub
    If e.Button <> Windows.Forms.MouseButtons.Right Then Exit Sub
    ContextMenuStrip1.Show(Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y)
    ContextMenuStrip1.Visible = True
  End Sub


Alors comme indiqué, si ma liste (2) est vide, je sors.
Ceci fonctionne très bien si je mets un msgBox préalable, il m'indique "liste2 = 0" et ça sort...

Mais... si j'enlève le msgbox, ben, le code ne tient plus comtpe du test, que la liste soit vide ou nom il m'ouvre le menu surgissant qui suite dans la séquence du code... Ah...

Bon... je me suis dit qu'il n'avait pas le temps... alors j'ai mis un doEvents, mais ça ne change rien...

Conclusion probable : il y a un conflit de code entre les dirrérentes procédures évènementailles portant sur cette liste, mais comme je n'ai pas fais le code, évidemment, je ne suis ps non plus très capable de retrouver le conflit...

Voici le code en entier, il est en construction :

Pour mémoire : il s'agit de deux listes, l'une de produits, l'autre de courses, les éléments peuvent donc par dragAndDrop passer d'un liste à l'autre, ensuite il y a des menus surgissant afin de gérer les listes (pour l'un création, modif, sup de produit), pour l'autre, la 2, là où est le problème (impression, quantité (automatique après dragAndDrop), impression, modif quantité (à venir)...

'
' courses form1
Option Explicit On
Imports System.IO
Imports System.Text

Public Class Form1
  Dim lindice As Integer
  Dim provenance As Byte = 0
  Public valide As Boolean
  Public produitPlusNombre As String
  Public typeForm3 As String

  Private Structure DDS
    Public ListBox As ListBox
    Public Item As String
    Public Index As Integer
  End Structure

  Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    AddHandler ListBox1.MouseDown, AddressOf ListBox_MouseDown
    AddHandler ListBox2.MouseDown, AddressOf ListBox_MouseDown
    AddHandler ListBox1.DragOver, AddressOf ListBox_DragOver
    AddHandler ListBox2.DragOver, AddressOf ListBox_DragOver
    AddHandler ListBox1.DragDrop, AddressOf ListBox_DragDrop
    AddHandler ListBox2.DragDrop, AddressOf ListBox_DragDrop
    ListBox1.Items.Clear() ' 32 maxi
    ListBox2.Items.Clear()
    ListBox1.AllowDrop = True
    ListBox2.AllowDrop = True
    Me.Left = 10
    Me.Top = 10
    Call litProduits()
    Call litCourses()
  End Sub

  Sub ListBox1_GiveFeedback(sender As Object, e As System.Windows.Forms.GiveFeedbackEventArgs) Handles ListBox1.GiveFeedback
    e.UseDefaultCursors = False
    Cursor.Current = Cursors.PanEast
  End Sub

  Sub ListBox2_GiveFeedback(sender As Object, e As System.Windows.Forms.GiveFeedbackEventArgs) Handles ListBox2.GiveFeedback
    e.UseDefaultCursors = False
    Cursor.Current = Cursors.PanWest
  End Sub

  Sub ListBox_MouseDown(ByVal sender As ListBox, ByVal e As System.Windows.Forms.MouseEventArgs)
    If sender.Items.Count > 0 Then
      Dim data As DDS
      data.Index = sender.IndexFromPoint(e.X, e.Y)
      If data.Index >= 0 Then
        sender.SelectedIndex = data.Index
        data.ListBox = sender
        provenance = 2
        If Len(Trim(sender.SelectedItem.ToString())) < 33 Then provenance = 1
        data.Item = sender.SelectedItem.ToString() ' contenu de la liste(i)
        Try
          sender.DoDragDrop(data, DragDropEffects.Move)
        Catch
          MsgBox(Err.Description & vbLf & Err.Number)
        End Try
      End If
    End If
  End Sub

  Sub ListBox_DragOver(ByVal sender As ListBox, ByVal e As System.Windows.Forms.DragEventArgs)
    If e.Data.GetDataPresent(GetType(DDS)) Then
      Dim data As DDS = e.Data.GetData(GetType(DDS))
      If data.ListBox Is sender Then
        e.Effect = DragDropEffects.None
        Exit Sub
      End If
      e.Effect = DragDropEffects.Move
    End If
  End Sub

  Sub ListBox_DragDrop(ByVal sender As ListBox, ByVal e As System.Windows.Forms.DragEventArgs)
    If e.Data.GetDataPresent(GetType(DDS)) Then
      Dim data As DDS = e.Data.GetData(GetType(DDS))
      If provenance = 1 Then
        Form2.Label1.Text = data.Item
        Form2.ShowDialog(Me)
        If valide = False Then Exit Sub
        data.Item = produitPlusNombre
      End If
      If provenance = 2 Then
        Dim trans As String = data.Item
        data.Item = Trim(Mid(trans, 1, 32))
      End If
      sender.Items.Add(data.Item)
      data.ListBox.Items.RemoveAt(data.Index)
      Call afficheCompteurs()
    End If
  End Sub

  Sub afficheCompteurs()
    ListBox1.Refresh()
    ListBox2.Refresh()
    Label1.Text = ListBox1.Items.Count
    Label2.Text = ListBox2.Items.Count
    Label5.Text = ListBox1.Items.Count + ListBox2.Items.Count
    Call faitLindex()
  End Sub

  Sub litProduits()
    ListBox1.Items.Clear()
    Try
      Dim p As New System.IO.StreamReader(CStr(My.Application.Info.DirectoryPath & "\produits.txt"))
      While p.Peek() >= 0
        ListBox1.Items.Add(p.ReadLine())
      End While
      p.Close()
    Catch ex As Exception
      MsgBox("Pas de liste des produit, voire régénérescence <!>  ", vbExclamation)
    End Try
    Call afficheCompteurs()
  End Sub

  Sub litCourses()
    ListBox2.Items.Clear()
    Try
      Dim p As New System.IO.StreamReader(CStr(My.Application.Info.DirectoryPath & "\courses.txt"))
      While p.Peek() >= 0
        ListBox2.Items.Add(p.ReadLine())
      End While
      p.Close()
    Catch ex As Exception
    End Try
    Call afficheCompteurs()
  End Sub

  Sub ecritProduit()
    Dim p1 As New System.IO.StreamWriter(CStr(My.Application.Info.DirectoryPath & "\produits.txt"))
    For i = 0 To ListBox1.Items.Count - 1
      p1.WriteLine(Trim(Mid(ListBox1.Items(i), 1, 32)))
    Next i
    p1.Close()
  End Sub

  Sub faitLindex()
    If ListBox1.Items.Count > 1 Then
      Dim i As Integer
      ListBox3.Items.Clear()
      For i = 0 To ListBox1.Items.Count - 1
        ListBox3.Items.Add(UCase(Mid(ListBox1.Items(i), 1, 1)))
      Next i
      For i = ListBox3.Items.Count - 1 To 1 Step -1
        If ListBox3.Items(i) = ListBox3.Items(i - 1) Then ListBox3.Items.RemoveAt(i)
      Next i
      ListBox3.Refresh()
    End If

    TextBox1.Text = ""
    For i = 0 To ListBox3.Items.Count - 1
      TextBox1.Text = TextBox1.Text & UCase(ListBox3.Items(i))
      TextBox1.Text = TextBox1.Text & LCase(ListBox3.Items(i))
    Next i

  End Sub

  Sub ecritCourses()
    Dim p1 As New System.IO.StreamWriter(CStr(My.Application.Info.DirectoryPath & "\courses.txt"))
    For i = 0 To ListBox2.Items.Count - 1
      p1.WriteLine(Trim(Mid(ListBox2.Items(i), 1, 36)))
    Next i
    p1.Close()
  End Sub

  Sub ImprimerLaListeDesCoursesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ImprimerLaListeDesCoursesToolStripMenuItem.Click
    If ListBox2.Items.Count < 1 Then Exit Sub
    lindice = 0
    Dim i As Integer
    i = MsgBox("Conformer l'impression de la liste des courses  ", vbQuestion + vbYesNo + vbDefaultButton2)
    If i <> vbYes Then Exit Sub
    Dim PageSetupDialog As New PageSetupDialog()
    PageSetupDialog.Document = PrintDocument1
    PageSetupDialog.PageSettings.Landscape = False
    Me.PrintDocument1.Print()
  End Sub

  Sub PrintDocument1_PrintPage(sender As System.Object, e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    Dim police As New Font("Courier New", 12, FontStyle.Regular)
    Dim yPos As Integer = 10 ' pixels
    Do While lindice < ListBox2.Items.Count
      e.Graphics.DrawString(ListBox2.Items(lindice), police, Brushes.Black, 10, yPos)
      Select Case lindice
        Case 60, 120, 180, 240, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900 ' 16 pages...
          e.HasMorePages = True
          lindice = lindice + 1
          Return
      End Select
      yPos = yPos + police.GetHeight
      lindice = lindice + 1
    Loop
  End Sub

  Sub SupprimerLaListeDesCoursesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SupprimerLaListeDesCoursesToolStripMenuItem.Click
    Dim i As Integer
    i = MsgBox("Supprimer la liste des courses en la réintégrant dans les produits  ", vbQuestion + vbYesNo + vbDefaultButton2)
    If i <> vbYes Then Exit Sub
    For i = 0 To ListBox2.Items.Count - 1
      ListBox1.Items.Add(Trim(Mid(ListBox2.Items(i), 1, 32)))
    Next i
    ListBox2.Items.Clear()
    Call afficheCompteurs()
  End Sub


  Sub ListBox2_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox2.MouseDown
    MsgBox(ListBox2.Items.Count)
    If ListBox2.Items.Count < 1 Then Exit Sub
    If e.Button <> Windows.Forms.MouseButtons.Right Then Exit Sub
    ContextMenuStrip1.Show(Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y)
    ContextMenuStrip1.Visible = True
  End Sub


  Sub ListBox3_DoubleClick(sender As Object, e As System.EventArgs) Handles ListBox3.DoubleClick
    Dim lettre1 As String = ListBox3.Items(ListBox3.SelectedIndex)
    Dim lettre2 As String = Chr(ListBox3.SelectedIndex + 97)
    Dim i As Integer
    For i = ListBox1.TopIndex To ListBox1.Items.Count - 1
      If lettre1 Mid(ListBox1.Items(i), 1, 1) Or lettre1 Mid(ListBox1.Items(i), 1, 1) Then
        ListBox1.TopIndex = i
        Exit Sub
      End If
    Next i
    For i = 0 To ListBox1.Items.Count - 1
      If lettre1 Mid(ListBox1.Items(i), 1, 1) Or lettre1 Mid(ListBox1.Items(i), 1, 1) Then
        ListBox1.TopIndex = i
        Exit Sub
      End If
    Next i
  End Sub

  Sub ListBox1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown
    If e.Button <> Windows.Forms.MouseButtons.Right Then Exit Sub
    If ListBox1.Items.Count = 0 Then
      ToolStripMenuItem2.Visible = False
      ToolStripMenuItem3.Visible = False
    End If
    ContextMenuStrip2.Show(Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y)
    ContextMenuStrip2.Visible = True
  End Sub

  Sub ToolStripMenuItem1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem1.Click
    typeForm3 = "créer"
    Form3.ShowDialog(Me)
    If typeForm3 = "" Then Exit Sub
  End Sub

  Sub ToolStripMenuItem2_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem2.Click
    If ListBox1.SelectedIndex < 0 Then
      MsgBox("Sélectionnez le produit à modifier  ", vbExclamation)
      Exit Sub
    End If
    typeForm3 = "modifier"
    Form3.ShowDialog(Me)
    If typeForm3 = "" Then Exit Sub
  End Sub

  Sub ToolStripMenuItem3_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItem3.Click
    Dim sup As Integer ' supprimer list1
    If ListBox1.SelectedIndex < 0 Then
      MsgBox("Sélectionnez le produit à supprimer  ", vbExclamation)
      Exit Sub
    End If
    sup = MsgBox("Supprimer ce produit : " & vbLf & vbLf & ListBox1.Items(ListBox1.SelectedIndex), vbQuestion + vbYesNo + vbDefaultButton2)
    If sup <> vbYes Then Exit Sub
    ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
    Call ecritCourses()
    Call afficheCompteurs()
  End Sub

  Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Dim i As Integer
    Call ecritProduit()
    Call ecritCourses()
    ListBox4.Items.Clear()
    For i = 0 To ListBox1.Items.Count - 1
      ListBox4.Items.Add(Trim(Mid(ListBox1.Items(i), 1, 32)))
    Next i
    For i = 0 To ListBox2.Items.Count - 1
      ListBox4.Items.Add(Trim(Mid(ListBox2.Items(i), 1, 32)))
    Next i
    Dim p As New System.IO.StreamWriter(CStr(My.Application.Info.DirectoryPath & "\produit_stock.txt"))
    For i = 0 To ListBox4.Items.Count - 1
      p.WriteLine(Trim(Mid(ListBox4.Items(i), 1, 32)))
    Next i
    p.Close()
  End Sub

End Class


Merci, cordialement, Joe.

24 réponses

Renfield Messages postés 17287 Date d'inscription mercredi 2 janvier 2002 Statut Modérateur Dernière intervention 27 septembre 2021 74
6 janv. 2012 à 23:50
supprime ce lien
vide la propriété ContextMenu (pas sur du nom) de ta ListBox

c'est cette unique ligne qui te pose un probleme


Renfield - Admin CodeS-SourceS - MVP Visual Basic & Spécialiste des RegExp
3
ucfoutu Messages postés 18038 Date d'inscription lundi 7 décembre 2009 Statut Modérateur Dernière intervention 11 avril 2018 211
4 janv. 2012 à 11:52
Bonjour,

C'est apparemment ta procédure LitCourses, lancée dans le Form_load, qui n'est pas encore terminée, je pense.


____________________
Réponse exacte ? => "REPONSE ACCEPTEE" pour faciliter les recherches d'autres forumeurs.
Pas d'aide en ligne installée ? ==> ne comptez pas sur moi pour simplement vous dire ce qu'elle contient
0
ucfoutu Messages postés 18038 Date d'inscription lundi 7 décembre 2009 Statut Modérateur Dernière intervention 11 avril 2018 211
4 janv. 2012 à 11:55
Essaye de n'habiliter ta listbox (par visible ou enabled) qu'à la fin de la procédure Litcourses


____________________
Réponse exacte ? => "REPONSE ACCEPTEE" pour faciliter les recherches d'autres forumeurs.
Pas d'aide en ligne installée ? ==> ne comptez pas sur moi pour simplement vous dire ce qu'elle contient
0
Utilisateur anonyme
4 janv. 2012 à 11:57
Salut Joe,

Pourquoi ne pas faire:
 Sub ListBox2_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox2.MouseDown
        If ListBox2.Items.Count > 0 Then
            If e.Button <> Windows.Forms.MouseButtons.Right Then Exit Sub
            ContextMenuStrip1.Show(Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y)
            ContextMenuStrip1.Visible = True
        End If
    End Sub


As-tu essayé?




CF2i - Guadeloupe
Ingénierie Informatique
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question
Utilisateur anonyme
4 janv. 2012 à 12:01
Bon je dis n'importe quoi... il est 7h du mat, j'ai pas pris mon café encore...

Ce que je t'ai mis c'est la même chose que ce que t'as fait...

Uc a raison c'est que ton listbox n'est pas encore rempli à ce moment précis (ListBox2.Items.Count est à zéro) .



CF2i - Guadeloupe
Ingénierie Informatique
0
cs_ShayW Messages postés 3253 Date d'inscription jeudi 26 novembre 2009 Statut Membre Dernière intervention 3 décembre 2019 57
4 janv. 2012 à 13:27
Bonjour et meilleur voeux
j'ai testé ça
Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown
  'MessageBox.Show(DirectCast(sender, ListBox).Items.Count.ToString)
If DirectCast(sender, ListBox).Items.Count < 1 Then
    Exit Sub
End If
If e.Button <> Windows.Forms.MouseButtons.Right Then
     Exit Sub
End If
End Sub


mettre un points d'arret
à la ligne
If DirectCast
lance le prog
si la listbox est vide
exit sub de la premiere condition
si la listbox n'est pas vide
si click avec bouton gauche
exit sub de la seconde condition
si bouton droit
continue
0
cs_ShayW Messages postés 3253 Date d'inscription jeudi 26 novembre 2009 Statut Membre Dernière intervention 3 décembre 2019 57
4 janv. 2012 à 13:30
plutot

Private Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown
 'MessageBox.Show(DirectCast(sender, ListBox).Items.Count.ToString)
 If DirectCast(sender, ListBox).Items.Count < 1 Then
     Exit Sub
 End If
 If e.Button <> Windows.Forms.MouseButtons.Right Then
    Exit Sub
 End If
        ContextMenuStrip1.Show(Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y)
        ContextMenuStrip1.Visible = True
    End Sub
0
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 4
4 janv. 2012 à 16:00
Merci pour les réponses, je vais voir dès que j'ai le temps...

Pour la liste, "non", à l'initialisation elle doit être inférieure à un, d'autant que justement elle est vide pour les essais (list2 de droite).
J'ai tenté d'inverser le code, de mettre un doEvents, rien n'y fait...

A mon avis, je persiste, il doit y avoir un conflit de priorité de procédure évènementielles, par exemple la procédure dragAndDrop qui passe devant la MouseDown (je n'ai pas regardé l'ordre des priorités), en plus c'est "Ramfield" qui m'a fait d'autorité le code en pur vbNet, alors déjà que je ne savais pas faire un dragAndDrop en vbNet, là c'est encore pire, je ne comprends rien, alors je n'ose pas toucher à son code, de peur de tout casser arg...

Je reviens, merci, à bientôt, Joe.
0
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 4
4 janv. 2012 à 19:57
ucfoutu :
Le load n'interfère pas car ma procédure qui n'est pas automatique, elle ne fonctionne que quand je fais mouse-down à droite, or je ne suis pas assez perfide pour cliquer droit au lancement du programme


acive
Merci de ta propositon, j'y ai pensé d'y aller à l'arme lourde, mais quand même, ce serait mieux de trouver la cause... d'autant que parfois ce genre de méthode occasionne par la suite d'autre problèmes


ShayW
Merci de ton code, qui ne fonctionne pas pour ce qu'il aurait aimé faire


Bon... je vais déposer le code en téléchargement, code sans danger, il se contente de jouer avec deux, trois fichiers à l'aide d'une liste de course dans son propre répertoire (bin), la procédure en cause est celle qui suit, qui normalement devrait inhiber le menu surgissant quand la liste est vide, ce que malheureusement le code n'arrive pas à faire :

 Sub ListBox2_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox2.MouseDown
    If ListBox2.Items.Count < 1 Then Exit Sub
    If e.Button <> Windows.Forms.MouseButtons.Right Then Exit Sub
    ContextMenuStrip1.Show(Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y)
    ContextMenuStrip1.Visible = True
  End Sub



http://cjoint.com/?0Aet5cYy5Ku


Merci, cordialement, Joe.
0
Renfield Messages postés 17287 Date d'inscription mercredi 2 janvier 2002 Statut Modérateur Dernière intervention 27 septembre 2021 74
5 janv. 2012 à 11:32
pas ouvert les autres Forms


Ton code pique encore un peu les yeux, l'ami...

valide, provenance, lindice, produitPlusNombre et typeForm3

n'ont rien a faire ici

rien ne t'interdit d'ajouter un parametre a ShowDialog de ta Form3

provenance est a placer dans le type DDS


Form2.Label1.Text = data.Item

NON!
on ne manipule pas ainsi les controles des autres forms...

faire par exemple :
If Form2.TesterItem(Me, data.Item) Then
en déclarant Public une méthode TesterItem dans Form2
Form2 renvoie alors Vrai/Faux, qui remplace ta variable 'valide'


Trop de Exit Sub, ca ne facilite pas la lecture.
inverse tes tests, englobe le code


dans ListBox1_MouseDown, pas besoin de passer par System.Windows.Forms.Cursor.Position.X
tu as les coordonnées de la souris dans le 'e' As MouseEventArgs


ListBox3.Items(ListBox3.SelectedIndex)
se dit :
ListBox3.Text (idem en VB6)

des efforts notables, mais encore beaucoup de VB6 la dedans :

If lettre1 Mid(ListBox1.Items(i), 1, 1) or lettre2 Mid(ListBox1.Items(i), 1, 1) Then
se dit:
If ListBox1.Items(i).ToString.StartsWith(lettre1, StringComparison.CurrentCultureIgnoreCase) Then


Select Case lindice
Case 60, 120, 180, 240, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900 ' 16 pages...
arithmetique de base : le Modulo (reste de la division entière) :
If lindice > 0 AndAlso (lindice Mod 60) = 0 Then

ainsi, on gère un nombre "illimité" de pages...


de même,

Dim p As New System.IO.StreamReader(CStr(My.Application.Info.DirectoryPath & "\courses.txt"))
While p.Peek() >= 0
ListBox2.Items.Add(p.ReadLine())
End While
p.Close()

se résume en cette seule ligne :

ListBox2.Items.AddRange(File.ReadAllLines("courses.txt"))


Ah, et ton souci, je ne le reproduit pas ...


'
' courses form1
Option Explicit On
Imports System.IO
Imports System.Text
Imports System.Windows.Forms

Public Class Form1
    Dim lindice As Integer
    Public produitPlusNombre As String

    Private Structure DDS
        Public ListBox As ListBox
        Public Item As String
        Public Index As Integer
        Public Provenance As Byte
    End Structure

    Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        AddHandler ListBox1.MouseDown, AddressOf ListBox_MouseDown
        AddHandler ListBox2.MouseDown, AddressOf ListBox_MouseDown
        AddHandler ListBox1.DragOver, AddressOf ListBox_DragOver
        AddHandler ListBox2.DragOver, AddressOf ListBox_DragOver
        AddHandler ListBox1.DragDrop, AddressOf ListBox_DragDrop
        AddHandler ListBox2.DragDrop, AddressOf ListBox_DragDrop
        ListBox1.Items.Clear() ' 32 maxi
        ListBox2.Items.Clear()
        ListBox1.AllowDrop = True
        ListBox2.AllowDrop = True
        Me.Left = 10
        Me.Top = 10
        Call litProduits()
        Call litCourses()
    End Sub

    Sub ListBox1_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles ListBox1.GiveFeedback
        e.UseDefaultCursors = False
        Cursor.Current = Cursors.PanEast
    End Sub

    Sub ListBox2_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles ListBox2.GiveFeedback
        e.UseDefaultCursors = False
        Cursor.Current = Cursors.PanWest
    End Sub

    Sub ListBox_MouseDown(ByVal sender As ListBox, ByVal e As MouseEventArgs)
        If sender.Items.Count > 0 Then
            Dim data As DDS
            data.Index = sender.IndexFromPoint(e.X, e.Y)
            If data.Index >= 0 Then
                sender.SelectedIndex = data.Index
                data.ListBox = sender
                If sender.Text.Trim.Length < 33 Then
                    data.Provenance = 1
                Else
                    data.Provenance = 2
                End If
                data.Item = sender.SelectedItem.ToString() ' contenu de la liste(i)
                Try
                    sender.DoDragDrop(data, DragDropEffects.Move)
                Catch Ex As Exception
                    MessageBox.Show(Ex.Message)
                End Try
            End If
        End If
    End Sub

    Sub ListBox_DragOver(ByVal sender As ListBox, ByVal e As DragEventArgs)
        If e.Data.GetDataPresent(GetType(DDS)) Then
            Dim data As DDS = e.Data.GetData(GetType(DDS))
            If data.ListBox Is sender Then
                e.Effect = DragDropEffects.None
                Exit Sub
            End If
            e.Effect = DragDropEffects.Move
        End If
    End Sub

    Sub ListBox_DragDrop(ByVal sender As ListBox, ByVal e As DragEventArgs)
        If e.Data.GetDataPresent(GetType(DDS)) Then
            Dim data As DDS = e.Data.GetData(GetType(DDS))
            If data.Provenance = 1 Then
                If Form2.TesterItem(Me, data.Item) Then
                    data.Item = produitPlusNombre
                ElseIf data.Provenance = 2 Then
                    data.Item = data.Item.padright(32).Substring(0, 32).Trim
                End If
                sender.Items.Add(data.Item)
                data.ListBox.Items.RemoveAt(data.Index)
                Call afficheCompteurs()
            End If
        End If
    End Sub

    Sub afficheCompteurs()
        ListBox1.Refresh()
        ListBox2.Refresh()
        Label1.Text = ListBox1.Items.Count
        Label2.Text = ListBox2.Items.Count
        Label5.Text = ListBox1.Items.Count + ListBox2.Items.Count
        Call faitLindex()
    End Sub

    Sub litProduits()
        Try
            ListBox1.Items.Clear()
            ListBox1.Items.AddRange(File.ReadAllLines("produits.txt"))
        Catch ex As Exception
            MessageBox.Show("Pas de liste des produit, voire régénérescence <!>" & Environment.NewLine & _
                            ex.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Finally
            Call afficheCompteurs()
        End Try
    End Sub

    Sub litCourses()
        Try
            ListBox2.Items.Clear()
            ListBox2.Items.AddRange(File.ReadAllLines("courses.txt"))
        Catch ex As Exception
            MessageBox.Show("Pas de liste courses" & Environment.NewLine & _
                            ex.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Finally
            Call afficheCompteurs()
        End Try
    End Sub

    Sub ecritProduit()
        Using p As TextWriter = New StreamWriter("produits.txt")
            For Each Item As String In ListBox1.Items
                p.WriteLine(Item.PadRight(32).Trim())
            Next Item
            p.Close()
        End Using
    End Sub

    Sub faitLindex()
        Dim sLetter As String
        If ListBox1.Items.Count > 0 Then
            ListBox3.Items.Clear()
            For Each Item As String In ListBox1.Items
                sLetter = Item.Substring(0, 1).ToUpper()
                If Not ListBox3.Items.Contains(sLetter) Then
                    ListBox3.Items.Add(sLetter)
                End If
            Next Item
        End If
    End Sub

    Sub ecritCourses()
        Using p As TextWriter = New StreamWriter("courses.txt")
            For Each Item As String In ListBox2.Items
                p.WriteLine(Item.PadRight(36).Substring(0, 36).Trim())
            Next Item
            p.Close()
        End Using
    End Sub

    Sub ImprimerLaListeDesCoursesToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ImprimerLaListeDesCoursesToolStripMenuItem.Click
        If ListBox2.Items.Count > 0 Then
            lindice = 0
            If MessageBox.Show("Confirmer l'impression de la liste des courses  ", "Imprimer la liste ?", _
                               MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
                               MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                Dim PageSetupDialog As New PageSetupDialog()
                PageSetupDialog.Document = PrintDocument1
                PageSetupDialog.PageSettings.Landscape = False
                Me.PrintDocument1.Print()
            End If
        End If
    End Sub

    Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim police As New Font("Courier New", 12, FontStyle.Regular)
        Dim yPos As Integer = 10 ' pixels
        Do While lindice < ListBox2.Items.Count
            e.Graphics.DrawString(ListBox2.Items(lindice), police, Brushes.Black, 10, yPos)
            If lindice > 0 AndAlso (lindice Mod 60) = 0 Then
                e.HasMorePages = True
                lindice = lindice + 1
                Return
            End If
            yPos = yPos + police.GetHeight
            lindice = lindice + 1
        Loop
    End Sub

    Sub SupprimerLaListeDesCoursesToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SupprimerLaListeDesCoursesToolStripMenuItem.Click
        If MessageBox.Show("Supprimer la liste des courses en la réintégrant dans les produits  ", _
                           "Confirmer la suppression ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = DialogResult.Yes Then
            For Each Item As String In ListBox2.Items
                ListBox1.Items.Add(Item.padright(32).Substring(0, 32).Trim)
            Next Item
            ListBox2.Items.Clear()
            Call afficheCompteurs()
        End If
    End Sub


    Sub ListBox2_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListBox2.MouseDown
        If ListBox2.Items.Count > 0 AndAlso e.Button = MouseButtons.Right Then
            ContextMenuStrip1.Show(e.Location.X, e.Location.Y)
            ContextMenuStrip1.Visible = True
        End If
    End Sub


    Sub ListBox3_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox3.DoubleClick
        Dim lettre1 As String = ListBox3.Text
        Dim i As Integer
        For i = ListBox1.TopIndex To ListBox1.Items.Count - 1
            If ListBox1.Items(i).ToString.StartsWith(lettre1, StringComparison.CurrentCultureIgnoreCase) Then
                ListBox1.TopIndex = i
                Exit Sub
            End If
        Next i
        For i = 0 To ListBox1.Items.Count - 1
            If ListBox1.Items(i).ToString.StartsWith(lettre1, StringComparison.CurrentCultureIgnoreCase) Then
                ListBox1.TopIndex = i
                Exit Sub
            End If
        Next i
    End Sub

    Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListBox1.MouseDown
        If e.Button = MouseButtons.Right Then
            If ListBox1.Items.Count = 0 Then
                ToolStripMenuItem2.Visible = False
                ToolStripMenuItem3.Visible = False
            End If
            ContextMenuStrip2.Show(e.Location.X, e.Location.Y)
            ContextMenuStrip2.Visible = True
        End If
    End Sub

    Sub ToolStripMenuItem1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ToolStripMenuItem1.Click
        Form3.ShowDialog(Me, "créer")
    End Sub

    Sub ToolStripMenuItem2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ToolStripMenuItem2.Click
        If ListBox1.SelectedIndex < 0 Then
            MessageBox.Show("Sélectionnez le produit à modifier  ", "Aucun item selectionné", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            Form3.ShowDialog(Me, "modifier")
        End If
    End Sub

    Sub ToolStripMenuItem3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ToolStripMenuItem3.Click
        If ListBox1.SelectedIndex < 0 Then
            MessageBox.Show("Sélectionnez le produit à supprimer", "Rien a supprimer", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        ElseIf MessageBox.Show("Supprimer ce produit : " & Environment.NewLine & Environment.NewLine & _
                               ListBox1.Text, "Confirmer la suppression", _
                               MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = .DialogResult.Yes Then
            ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
            Call ecritCourses()
            Call afficheCompteurs()
        End If
    End Sub

    Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
        Dim Item As String
        Call ecritProduit()
        Call ecritCourses()

        Using p As TextWriter = New StreamWriter("produit_stock.txt")
            For Each Item In ListBox1.Items
                p.WriteLine(Item.PadRight(32).Substring(0, 32).Trim())
            Next Item
            For Each Item In ListBox2.Items
                p.WriteLine(Item.PadRight(32).Substring(0, 32).Trim())
            Next Item
            p.Close()
        End Using
    End Sub

End Class


Renfield - Admin CodeS-SourceS - MVP Visual Basic & Spécialiste des RegExp
0
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 4
6 janv. 2012 à 11:54
Cher ami Reynald,

Ton truc y marche pas !

Zabotache !

If ListBox2.Items.Count > 0 AndAlso e.Button = MouseButtons.Right Then
 ContextMenuStrip1.Show(e.Location.X, e.Location.Y)
 ContextMenuStrip1.Visible = True
End If


Veux-tu bien le tester puisque tu peux télécharge le code, tu verras que la liste vide fait surgir le menu, rien n'a changé

Je persiste à subodorer qu'il y a un conflit de priorité de procédures évènementielles, et qu'une de tes procédure (dont je ne comprends rien), pique sans doute la priorité a ma listBox2_MousDown, notamment le début du dragAndDrop que tu gères comence par un MouseDown, je ne serais pas étonné que le problème soit là

Restant dans l'attente de tes directives, je te prie de croire à l'assurance de ma considération.

Joe.
0
Renfield Messages postés 17287 Date d'inscription mercredi 2 janvier 2002 Statut Modérateur Dernière intervention 27 septembre 2021 74
6 janv. 2012 à 12:05
je ne peux pas lancer ton projet, raison pour laquelle je repart d'une Form perso...

Error 1 'IContainer' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\Form1.Designer.vb 18 27 courses
Error 2 'Container' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\Form1.Designer.vb 25 25 courses
Error 3 'ComponentResourceManager' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\Form1.Designer.vb 26 22 courses
Error 4 'IContainer' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\Form2.Designer.vb 18 27 courses
Error 5 'ComponentResourceManager' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\Form2.Designer.vb 25 22 courses
Error 6 'IContainer' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\Form3.Designer.vb 18 27 courses
Error 7 'ComponentResourceManager' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\Form3.Designer.vb 25 22 courses
Error 8 'GeneratedCodeAttribute' is ambiguous in the namespace 'System.CodeDom.Compiler'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Resources.Designer.vb 25 6 courses
Error 9 'EditorBrowsableAttribute' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Resources.Designer.vb 38 10 courses
Error 10 'EditorBrowsableAttribute' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Resources.Designer.vb 53 10 courses
Error 11 'GeneratedCodeAttribute' is ambiguous in the namespace 'System.CodeDom.Compiler'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Settings.Designer.vb 18 6 courses
Error 12 'EditorBrowsableAttribute' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Settings.Designer.vb 19 6 courses
Error 13 'ApplicationSettingsBase' is ambiguous in the namespace 'System.Configuration'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Settings.Designer.vb 21 18 courses
Error 14 'ApplicationSettingsBase' is ambiguous in the namespace 'System.Configuration'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Settings.Designer.vb 23 62 courses
Error 15 'EditorBrowsableAttribute' is ambiguous in the namespace 'System.ComponentModel'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Settings.Designer.vb 31 68 courses
Error 16 'Save' is not a member of 'courses.My.MySettings'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Settings.Designer.vb 34 17 courses
Error 17 'HelpKeywordAttribute' is ambiguous in the namespace 'System.ComponentModel.Design'. C:\Documents and Settings\rthomas.BUDAPLAN\Mes documents\Downloads\courses\My Project\Settings.Designer.vb 66 10 courses


Renfield - Admin CodeS-SourceS - MVP Visual Basic & Spécialiste des RegExp
0
Renfield Messages postés 17287 Date d'inscription mercredi 2 janvier 2002 Statut Modérateur Dernière intervention 27 septembre 2021 74
6 janv. 2012 à 12:08
viré la référence 'system'
et ca compile, now ...

trop fort .Net

j'intègre mon code, te nettoie tout ca et repost

Renfield - Admin CodeS-SourceS - MVP Visual Basic & Spécialiste des RegExp
0
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 4
6 janv. 2012 à 12:30
Reynald,

Pourquoi tu ne peux ps le lancer, tu n'as pas vbNet10 ?

En fait moi je voulais un truc simple vb6 dans vbNet, genre :


dim vientDe as byte = 0
'
list1_mouseDown
vientde = 1

list1_over
if vientde <> 1 exit sub

list1_drop
met dans list2
' ----------------

list2_mouseDown
vientde = 2

list2_over
if vientde <> 2 exit sub

list2_drop
met dans list1


*

Voici ce que j'ai pour vb6, que je sais faire et qui marche :


DRAG AND DROP (glisser et poser) entre 2 listes
-----------------------------------------------
Pour chaque liste 3 évènements
MouseDown (choix)
DragOver (Source glissement)
DragDrop (Source poser)
La manipe entre liste se fait dans le DragDrop
si test Is Source est ok...

Sub List1_MouseDown(Button...
List1.Drag vbBeginDrag

Sub List1_DragOver(Source...
If (Source Is List1) Or (Source Is List2) Then
Source.DragIcon = Picture1.Picture

Sub List2_DragDrop(Source...
If Source <> List2 Then exit sub
List1.AddItem List2.List(List2.ListIndex)
List1.Refresh
List2.RemoveItem List2.ListIndex


Et ben je cherche un code vbNet le plus proche de ça

Cordialement, Joe.
0
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 4
6 janv. 2012 à 12:33
Je ne cherche pas à faire du vbNet, je m'en balance, je cherche à mettre du code dans vbNet, le plus possible vb6 (que je connais) pour que ça marche, pas davantage
0
Renfield Messages postés 17287 Date d'inscription mercredi 2 janvier 2002 Statut Modérateur Dernière intervention 27 septembre 2021 74
6 janv. 2012 à 12:46
vu ton souci...
le contextMenuStrip s'affiche de lui même a cause du lien :

Me.ListBox2.ContextMenuStrip = Me.ContextMenuStrip1

Renfield - Admin CodeS-SourceS - MVP Visual Basic & Spécialiste des RegExp
0
Renfield Messages postés 17287 Date d'inscription mercredi 2 janvier 2002 Statut Modérateur Dernière intervention 27 septembre 2021 74
6 janv. 2012 à 13:05
je tourne en 2008, doit venir de là mes soucis avec ton code

le plus possible vb6 (que je connais) pour que ça marche


même en VB6 on pouvait mal concevoir ses applications ^^

et lire/ecrire le contenu des variables ou des controles des autres forms, ca fait partie des choses a ne pas faire...

regarde la méthode ChangerQuantite de Form2 pour t'en convaincre...

Form2: (la encore, les handlers permettent de factoriser le code)
'
' courses form 2
Option Explicit On

Public Class Form2
    Sub Form2_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        AddHandler Button0.Click, AddressOf Button_Click
        AddHandler Button1.Click, AddressOf Button_Click
        AddHandler Button2.Click, AddressOf Button_Click
        AddHandler Button3.Click, AddressOf Button_Click
        AddHandler Button4.Click, AddressOf Button_Click
        AddHandler Button5.Click, AddressOf Button_Click
        AddHandler Button6.Click, AddressOf Button_Click
        AddHandler Button7.Click, AddressOf Button_Click
        AddHandler Button8.Click, AddressOf Button_Click
        AddHandler Button9.Click, AddressOf Button_Click
    End Sub

    Public Function ChangerQuantite(ByVal Form1 As Form1, ByVal Item As String, Optional ByVal DefaultValue As Integer = 1) As Integer
        Label1.Text = Item
        Label2.Text = DefaultValue.ToString()
        DialogResult = DialogResult.Cancel

        ShowDialog(Form1) '# Mettre la StartupPosition à CenterParent pour centrer le présent formulaire...

        Dim Valeur As Integer = DefaultValue
        '# Validation de la valeur saisie
        If DialogResult = DialogResult.OK Then
            If Integer.TryParse(Label2.Text, Valeur) Then
                If Valeur = 0 Or Valeur > 99 Then
                    Valeur = DefaultValue
                End If
            End If
        End If
        Me.Dispose()
        Return Valeur
    End Function

    Sub Button11_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button11.Click
        Label2.Text = String.Empty ' gomme
    End Sub

    Sub Button12_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button12.Click
        Me.DialogResult = DialogResult.OK
        Me.Close()
    End Sub

    Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
        If Len(Label2.Text) 0 Or Label2.Text "0" Then
            Label2.Text = sender.Text
        End If
        If Len(Label2.Text) < 2 Then
            Label2.Text = Label2.Text & sender.Text
        End If
    End Sub
End Class



Form3: (code a finaliser autour du renvoi des info...)
'
' courses form3 ajout ou modif
Option Explicit On

Public Class Form3
    Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AddHandler Button2.Click, AddressOf Button_Click
        AddHandler Button3.Click, AddressOf Button_Click
        AddHandler Button4.Click, AddressOf Button_Click
        AddHandler Button5.Click, AddressOf Button_Click
        AddHandler Button6.Click, AddressOf Button_Click
    End Sub

    Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        TextBox1.Text &= sender.Text
    End Sub

    Public Overloads Function ShowDialog(ByVal type As String) As DialogResult
        Select Case type
            Case "créer"
                Label1.Visible = False
                Label2.Text = "CREATION"
            Case "modifier"
                Label1.Visible = True
                Label2.Text = "MODIFICATION"
        End Select
        Return ShowDialog()
    End Function
End Class



et Form1:
'
' courses form1
Option Explicit On
Imports System.Windows.Forms
Imports System.IO
Imports System.Text

Public Class Form1
    Dim lindice As Integer

    Private Structure DDS
        Public ListBox As ListBox
        Public Item As String
        Public Index As Integer
    End Structure

    Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AddHandler ListBox1.MouseDown, AddressOf ListBox_MouseDown
        AddHandler ListBox2.MouseDown, AddressOf ListBox_MouseDown
        AddHandler ListBox1.DragOver, AddressOf ListBox_DragOver
        AddHandler ListBox2.DragOver, AddressOf ListBox_DragOver
        AddHandler ListBox1.DragDrop, AddressOf ListBox_DragDrop
        AddHandler ListBox2.DragDrop, AddressOf ListBox_DragDrop
        ListBox1.Items.Clear() ' 32 maxi
        ListBox2.Items.Clear()
        ListBox1.AllowDrop = True
        ListBox2.AllowDrop = True
        Me.Left = 10
        Me.Top = 10
        Call litProduits()
        Call litCourses()
    End Sub

    Sub ListBox1_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles ListBox1.GiveFeedback
        e.UseDefaultCursors = False
        Cursor.Current = Cursors.PanEast
    End Sub

    Sub ListBox2_GiveFeedback(ByVal sender As Object, ByVal e As GiveFeedbackEventArgs) Handles ListBox2.GiveFeedback
        e.UseDefaultCursors = False
        Cursor.Current = Cursors.PanWest
    End Sub

    Sub ListBox_MouseDown(ByVal sender As ListBox, ByVal e As MouseEventArgs)
        If sender.Items.Count > 0 Then
            Dim data As DDS
            data.Index = sender.IndexFromPoint(e.X, e.Y)
            If data.Index >= 0 Then
                sender.SelectedIndex = data.Index
                data.ListBox = sender
                data.Item = sender.Text.Trim ' contenu de la liste(i)
                Try
                    sender.DoDragDrop(data, DragDropEffects.Move)
                Catch
                    MsgBox(Err.Description & vbLf & Err.Number)
                End Try
            End If
        End If
    End Sub

    Sub ListBox_DragOver(ByVal sender As ListBox, ByVal e As DragEventArgs)
        If e.Data.GetDataPresent(GetType(DDS)) Then
            Dim data As DDS = e.Data.GetData(GetType(DDS))
            If data.ListBox Is sender Then
                e.Effect = DragDropEffects.None
                Exit Sub
            End If
            e.Effect = DragDropEffects.Move
        End If
    End Sub

    Sub ListBox_DragDrop(ByVal destination As ListBox, ByVal e As DragEventArgs)
        If e.Data.GetDataPresent(GetType(DDS)) Then
            Dim data As DDS = e.Data.GetData(GetType(DDS))
            If destination Is ListBox2 Then
                data.Item = data.Item.PadRight(34) & Form2.ChangerQuantite(Me, data.Item).ToString()
            Else
                data.Item = data.Item.PadRight(32).Substring(0, 32).Trim
            End If
            destination.Items.Add(data.Item)
            data.ListBox.Items.RemoveAt(data.Index)
            Call afficheCompteurs()
        End If
    End Sub

    Sub afficheCompteurs()
        ListBox1.Refresh()
        ListBox2.Refresh()
        Label1.Text = ListBox1.Items.Count
        Label2.Text = ListBox2.Items.Count
        Label5.Text = ListBox1.Items.Count + ListBox2.Items.Count
        Call faitLindex()
    End Sub

    Sub litProduits()
        Try
            ListBox1.Items.Clear()
            ListBox1.Items.AddRange(File.ReadAllLines("produits.txt"))
        Catch ex As Exception
            MessageBox.Show("Pas de liste des produit, voire régénérescence <!>" & Environment.NewLine & _
                            ex.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Finally
            Call afficheCompteurs()
        End Try
    End Sub

    Sub litCourses()
        Try
            ListBox2.Items.Clear()
            ListBox2.Items.AddRange(File.ReadAllLines("courses.txt"))
        Catch ex As Exception
            MessageBox.Show("Pas de liste courses" & Environment.NewLine & _
                            ex.Message, "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Finally
            Call afficheCompteurs()
        End Try
    End Sub

    Sub ecritProduit()
        Using p As TextWriter = New StreamWriter("produits.txt")
            For Each Item As String In ListBox1.Items
                p.WriteLine(Item.PadRight(32).Trim())
            Next Item
            p.Close()
        End Using
    End Sub

    Sub faitLindex()
        Dim sLetter As String
        If ListBox1.Items.Count > 0 Then
            ListBox3.Items.Clear()
            For Each Item As String In ListBox1.Items
                sLetter = Item.Substring(0, 1).ToUpper()
                If Not ListBox3.Items.Contains(sLetter) Then
                    ListBox3.Items.Add(sLetter)
                End If
            Next Item
        End If
    End Sub

    Sub ecritCourses()
        Using p As TextWriter = New StreamWriter("courses.txt")
            For Each Item As String In ListBox2.Items
                p.WriteLine(Item.PadRight(36).Substring(0, 36).Trim())
            Next Item
            p.Close()
        End Using
    End Sub

    Sub ImprimerLaListeDesCoursesToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ImprimerLaListeDesCoursesToolStripMenuItem.Click
        If ListBox2.Items.Count > 0 Then
            lindice = 0
            If MessageBox.Show("Confirmer l'impression de la liste des courses  ", "Imprimer la liste ?", _
                               MessageBoxButtons.YesNo, MessageBoxIcon.Question, _
                               MessageBoxDefaultButton.Button2) = Windows.Forms.DialogResult.Yes Then
                Dim PageSetupDialog As New PageSetupDialog()
                PageSetupDialog.Document = PrintDocument1
                PageSetupDialog.PageSettings.Landscape = False
                Me.PrintDocument1.Print()
            End If
        End If
    End Sub

    Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim police As New Font("Courier New", 12, FontStyle.Regular)
        Dim yPos As Integer = 10 ' pixels
        Do While lindice < ListBox2.Items.Count
            e.Graphics.DrawString(ListBox2.Items(lindice), police, Brushes.Black, 10, yPos)
            Select Case lindice
                Case 60, 120, 180, 240, 300, 360, 420, 480, 540, 600, 660, 720, 780, 840, 900 ' 16 pages...
                    e.HasMorePages = True
                    lindice = lindice + 1
                    Return
            End Select
            yPos = yPos + police.GetHeight
            lindice = lindice + 1
        Loop
    End Sub

    Sub SupprimerLaListeDesCoursesToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SupprimerLaListeDesCoursesToolStripMenuItem.Click
        Dim i As Integer
        i = MsgBox("Supprimer la liste des courses en la réintégrant dans les produits  ", vbQuestion + vbYesNo + vbDefaultButton2)
        If i <> vbYes Then Exit Sub
        For i = 0 To ListBox2.Items.Count - 1
            ListBox1.Items.Add(Trim(Mid(ListBox2.Items(i), 1, 32)))
        Next i
        ListBox2.Items.Clear()
        Call afficheCompteurs()
    End Sub


    Sub ListBox2_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListBox2.MouseDown
        If ListBox2.Items.Count < 1 Then Exit Sub
        If e.Button <> Windows.Forms.MouseButtons.Right Then Exit Sub
        ContextMenuStrip1.Show(Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y)
        ContextMenuStrip1.Visible = True
    End Sub

    Sub ListBox3_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles ListBox3.DoubleClick
        Dim lettre1 As String = ListBox3.Text
        Dim i As Integer
        For i = ListBox1.TopIndex To ListBox1.Items.Count - 1
            If ListBox1.Items(i).ToString.StartsWith(lettre1, StringComparison.CurrentCultureIgnoreCase) Then
                ListBox1.TopIndex = i
                Exit Sub
            End If
        Next i
        For i = 0 To ListBox1.Items.Count - 1
            If ListBox1.Items(i).ToString.StartsWith(lettre1, StringComparison.CurrentCultureIgnoreCase) Then
                ListBox1.TopIndex = i
                Exit Sub
            End If
        Next i
    End Sub

    Sub ListBox1_MouseDown(ByVal sender As Object, ByVal e As MouseEventArgs) Handles ListBox1.MouseDown
        If e.Button <> Windows.Forms.MouseButtons.Right Then Exit Sub
        If ListBox1.Items.Count = 0 Then
            ToolStripMenuItem2.Visible = False
            ToolStripMenuItem3.Visible = False
        End If
        ContextMenuStrip2.Show(Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y)
        ContextMenuStrip2.Visible = True
    End Sub

    Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles ToolStripMenuItem1.Click
        Form3.ShowDialog("créer")
    End Sub

    Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles ToolStripMenuItem2.Click
        If ListBox1.SelectedIndex < 0 Then
            MessageBox.Show("Sélectionnez le produit à modifier  ", "Aucun item selectionné", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            Form3.ShowDialog("modifier")
        End If
    End Sub

    Sub ToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles ToolStripMenuItem3.Click
        If ListBox1.SelectedIndex < 0 Then
            MessageBox.Show("Sélectionnez le produit à supprimer", "Rien a supprimer", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        ElseIf MessageBox.Show("Supprimer ce produit : " & Environment.NewLine & Environment.NewLine & _
                               ListBox1.Text, "Confirmer la suppression", _
                               MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = DialogResult.Yes Then
            ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
            Call ecritCourses()
            Call afficheCompteurs()
        End If
    End Sub

    Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.FormClosing
        Dim Item As String
        Call ecritProduit()
        Call ecritCourses()

        Using p As TextWriter = New StreamWriter("produit_stock.txt")
            For Each Item In ListBox1.Items
                p.WriteLine(Item.PadRight(32).Substring(0, 32).Trim())
            Next Item
            For Each Item In ListBox2.Items
                p.WriteLine(Item.PadRight(32).Substring(0, 32).Trim())
            Next Item
            p.Close()
        End Using
    End Sub

End Class


j'ai supprimé la variable 'provenance'
utilises le premier parametre des events : l'objet qui a déclenché l'event...!


Renfield - Admin CodeS-SourceS - MVP Visual Basic & Spécialiste des RegExp
0
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 4
6 janv. 2012 à 13:39
Oui mais :

Me.ListBox2.ContextMenuStrip = Me.ContextMenuStrip1

C'est l'association normale de la propriété de la liste avec un menu contextuel, c'est toujours ainsi dans ce cas je pense.

Le problème est autre, à savoir, comment lui dire de ne s'afficher que dans certaines conditions ???

Car si j'écris ce code (juste un msgBox en plus :

Sub ListBox2_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox2.MouseDown
 MsgBox("0")
 If ListBox2.Items.Count > 0 AndAlso e.Button = MouseButtons.Right Then
  ContextMenuStrip1.Show(e.Location.X, e.Location.Y)
  ContextMenuStrip1.Visible = True
 End If
End Sub


Je ne suis pas de ton avis car si le fait de déclarer un menu dans un propriété interdisait tout action sur ce menu, en lespèce qu'il s'affiche quoi qu'il arrive, et bien le fait de mettre préalablement un MsgBox n'y changerait rien, or là ça change tout ! On dirait qu'autre chose commande la procédure, un évènement que je ne sais identifier.

Par exemple si j'écris :
textbox1.text="bonjour"

et si ensuite j'écris :
msgbox("le bonjour arrive")
textbox1.text="bonjour"

Dans ls deux cas tu auras le bonjour du texte, le msg n'y change rien.

Or là le msgBox se comporte involontairement comme si en bloquant l'exécution du code, ça laissait le temps de dépiler certaines instructions qui de facto ne s'exécuteraient plus (non affichage du menu surgissant).

Si dans la list1 je fais la même chose ça marche bien (je vide la liste) :

If ListBox1.Items.Count < 1 Then Exit Sub ' DANS LA LISTE UN CA MARCHE !


Attention, une fois la liste vide, comme il y a un auto-enregistrement en fin on perd les datas, il faut la recharger comme suit :
- Dans le dossier de l'application, copier le contenu du fichier :
copie produits.txt
Coller la copie dans
... bin\debug\produits.txt

Il y a un problème de différence de codage de fichier, je verrai ça après avec une moulinette...

Alors pourquoi ça marche dans une liste et pas dans l'autre, ah ?

Cordialement, Joe.
0
ehjoe Messages postés 728 Date d'inscription samedi 4 avril 2009 Statut Membre Dernière intervention 30 mars 2014 4
6 janv. 2012 à 13:44
suite,

Est-ce que le menu surgissant reste inactif quand la liste 2 est vide désormais ?
0
Renfield Messages postés 17287 Date d'inscription mercredi 2 janvier 2002 Statut Modérateur Dernière intervention 27 septembre 2021 74
6 janv. 2012 à 14:24
le MsgBox créé une rupture dans le focus et donc dans celui des events
le traitement classique du menu n'est pas priss en compte : le menu ne s'affiche pas.

le lien a supprimer, qui existe entre le menu et la listbox est là pour les cas 'classiques'. Pour que .Net affiche le menu lors du click droit.

en associant un ContextMenu et un controle, pas une ligne de code n'est requise pour afficher ledit menu.

dans ton cas, puisque tu souhaites controller l'affichage (et qu'a fortiori tu l'affiches toi même), ce lien est inutile.



Renfield - Admin CodeS-SourceS - MVP Visual Basic & Spécialiste des RegExp
0
Rejoignez-nous