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 :

DatagridViewCell personalisée et constructeur paramétré


Sujet :

VB.NET

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Homme Profil pro
    Inscrit en
    Mai 2010
    Messages
    132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Australie

    Informations professionnelles :
    Secteur : Bâtiment

    Informations forums :
    Inscription : Mai 2010
    Messages : 132
    Par défaut DatagridViewCell personalisée et constructeur paramétré
    Bonjour,

    Je créer des datagridviewcolumn personalisées (%, date, booleen) et les datagridviewcell qui vont avec.

    Dans le cas de la colonne qui fait des progressbar pour les données pourcentage, je voudrais créer plusieurs rendu en fonction des propriétés de la datagridviewcell.

    Et pour cela j'ai fait un constructeur New() de la datagridviewcell AVEC des paramètres. Il est bien appelé quand je construis la colonne, mais le constructeur New() SANS paramètre est quand même appelé plus tard dans l'exécution et semble écrasé le précédent.



    J'ai donc créé une datagridviewpercentcell héritée de datagridviewtextboxcell, avec des propriétés supplémentaires:

    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
     
    Public Class DatagridviewProgressCell
        Inherits DataGridViewTextBoxCell
     
        Public Property TwoColors As Boolean = False
        Public Property PositiveAndDefaultColor As Color = Color.Green
        Public Property NegativeColor As Color = Color.Red
     
        Public Sub New()
            ValueType = Type.GetType("Double")
        End Sub
        Public Sub New(ByVal TwoColors As Boolean)
            ValueType = Type.GetType("Double")
            Me.TwoColors = TwoColors
        End Sub
     
        Public Overrides sub paint blahblah...
            Paint blah blah
            if TwoColors = True then
                DoThat
            Else
                DoThis
            End If
        end sub
    Public Overrides sub getformattedvalue blahblah...
     
    End Class
    La construction fonctionne mais ne prendra jamais en compte le constructuer paramétré. Les valeurs initiales des propriétés sont toujours utilisée...


    une idée?
    merci,

    Zebrette

  2. #2
    Membre expérimenté
    Avatar de Sadar
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Janvier 2005
    Messages
    49
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 58
    Localisation : Belgique

    Informations professionnelles :
    Activité : Développeur .NET
    Secteur : Biens de consommation

    Informations forums :
    Inscription : Janvier 2005
    Messages : 49
    Par défaut
    S'il est rappelé plus tard, alors a un autre endroit du code (hors class), le rappelle a nouveau par un changement de propriété (ce bout de code n'est pas suffisant pour trouver le phénomène de boucle).

    Ceci est une idée, mais une autre serait de ne pas utiliser New sans paramètre et déclarer en début de class la variable Valuetype avec valeur par défaut Type.get("Double")

    As-tu fait un debuger pas à pas sur l'ensemble, enfin oui je suppose et que dit-il ?

  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
    Bonjour zebrette
    ca me rapelle zebra crossing.....passons.
    Tout depend comment tu as organise tes constructeurs dans les 2 classes qui sont necessaires pour personnaliser le paintaing savoir :
    -DataGridViewProgressColumn
    -DataGridViewProgressCell
    Le constructeur par defaut classe ProgressColumn appelle le constructeur par defaut classe ProgressCell.
    Le constructeur parametre classe ProgressColumn appelle son constructeur par defaut MyBase mais avec une reference sur le constructeur parametre classe ProgressCell.
    Enfin il faut heriter de DataGridViewColumn au lieu de TextBoxColumn.
    Cela suffit pour initiliaser correctement la classe ProgressCell.
    Note au passage egalement que la prop TwoColors doit etre initilalisee correctement dans les 2 constructeurs de ProgressCell.

    Bref pour ne pas blaher ....blaher.......
    Voici le code exemple inspiree d'un article MSDN "How to: Disable Buttons in a Button Column in the Windows Forms DataGridView Control" dont le lien figure plus bas :
    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
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
     
    'Code du WinForm 
    Public Class frmProgressColumn
        Private WithEvents dataGridView1 As New DataGridView()
        Public Sub New()
            ' Cet appel est requis par le Concepteur Windows Form.
            InitializeComponent()
     
            'Ajoutez une initialisation quelconque après l'appel InitializeComponent().
     
            Me.AutoSize = True
        End Sub
     
        Private Sub frmProgressColumn_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            'Active les TextBoxes avec le contructeur  parametre ....blah blah.... 
            'BackGround sera  Rouge au lieu de Vert par defaut
            Dim objTwoColors As Boolean = True
            Dim column0 As New DataGridViewCheckBoxColumn()
            Dim column1 As New DataGridViewProgressColumn(objTwoColors)
            column0.Name = "CheckBoxes"
            column1.Name = "TexBoxes"
            dataGridView1.Columns.Add(column0)
            dataGridView1.Columns.Add(column1)
     
            dataGridView1.RowCount = 8
            dataGridView1.AutoSize = True
            dataGridView1.AllowUserToAddRows = False
            dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = _
                DataGridViewContentAlignment.MiddleCenter
     
            ' Set the text for each button.
            Dim i As Integer
            For i = 0 To dataGridView1.RowCount - 1
                dataGridView1.Rows(i).Cells("TexBoxes").Value = _
                    "myTextBox " + i.ToString()
            Next i
     
            Me.Controls.Add(dataGridView1)
        End Sub
        ' This event handler manually raises the CellValueChanged event
        ' by calling the CommitEdit method.
        Sub dataGridView1_CurrentCellDirtyStateChanged( _
            ByVal sender As Object, ByVal e As EventArgs) _
            Handles dataGridView1.CurrentCellDirtyStateChanged
     
            If dataGridView1.IsCurrentCellDirty Then
                dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
            End If
        End Sub
        ' If a check box cell is clicked, this event handler disables  
        ' or enables the TextBox in the same row as the clicked cell.
        Public Sub dataGridView1_CellValueChanged(ByVal sender As Object, _
            ByVal e As DataGridViewCellEventArgs) _
            Handles dataGridView1.CellValueChanged
     
            If dataGridView1.Columns(e.ColumnIndex).Name = "CheckBoxes" Then
                Dim textboxCell As DataGridViewProgressCell = _
                    CType(dataGridView1.Rows(e.RowIndex).Cells("TexBoxes"),  _
                    DataGridViewProgressCell)
     
                Dim checkCell As DataGridViewCheckBoxCell = _
                    CType(dataGridView1.Rows(e.RowIndex).Cells("CheckBoxes"),  _
                    DataGridViewCheckBoxCell)
                'bascule TwoColors => Not CheckBox.Value
                textboxCell.TwoColors = Not CType(checkCell.Value, [Boolean])
     
                dataGridView1.Invalidate()
            End If
        End Sub
    End Class
     
    'Code du fichier classe  DataGridViewProgressColumn
    'NB: importer VisualStyles sinon 
    'la couleur SystemColors.GrayText pour avoir le disabled 
    'ne compilera
    Imports System.Windows.Forms.VisualStyles
    Public Class DataGridViewProgressColumn
        Inherits DataGridViewColumn
     
        ' Constructeur par defaut 
        ' appelle le constructeur par defaut de la Cellule 
        Public Sub New()
            Me.CellTemplate = New DataGridViewProgressCell()
        End Sub
        ' Constructeur parametre 
        ' appelle le constructeur parametre  de la Cellule 
        Public Sub New(ByVal objTwoColors As Boolean)
            MyBase.New(New DataGridViewProgressCell(objTwoColors))
        End Sub
    End Class
    Public Class DataGridViewProgressCell
        Inherits DataGridViewTextBoxCell
     
        ' By default, disable m_TwoColors => False.
        ' correspond à notre PositiveAndDefaultColor(Green)
        Public Sub New()
            Me.ValueType = Type.GetType("Boolean")
            Me.m_TwoColors = False
        End Sub
        ' Constructeur parametre 
        'Attention !: ici pas de reference à MyBase sinon c'est rate
        Public Sub New(ByVal TwoColors As Boolean)
            ValueType = Type.GetType("Boolean")
            Me.m_TwoColors = TwoColors
        End Sub
        'Nos proprietes personnelles 
        Private m_TwoColors As Boolean
        Public Property TwoColors() As Boolean
            Get
                Return m_TwoColors
            End Get
            Set(ByVal value As Boolean)
                m_TwoColors = value
            End Set
        End Property
        Private m_PositiveAndDefaultColor As Color = Color.Green
        Public Property PositiveAndDefaultColor() As Color
            Get
                Return m_PositiveAndDefaultColor
            End Get
            Set(ByVal value As Color)
                m_PositiveAndDefaultColor = value
            End Set
        End Property
        Private m_NegativeColor As Color = Color.Red
        Public Property NegativeColor() As Color
            Get
                Return m_NegativeColor
            End Get
            Set(ByVal value As Color)
                m_NegativeColor = value
            End Set
        End Property
        'Attention: ne pas oublier la methode Clone qui doit 
        'dupliquer nos proprietes  pour chaque cellule de notre colonne
        ' Override the Clone method so that the :
        'Enabled ,PositiveAndDefaultColor and NegativeColor properties are copied.
     
        Public Overrides Function Clone() As Object
            Dim Cell As DataGridViewProgressCell = _
                CType(MyBase.Clone(), DataGridViewProgressCell)
            Cell.TwoColors = Me.TwoColors
            Cell.NegativeColor = Me.NegativeColor
            Cell.PositiveAndDefaultColor = Me.PositiveAndDefaultColor
            Return Cell
        End Function
     
        Protected Overrides Sub Paint(ByVal graphics As Graphics, _
           ByVal clipBounds As Rectangle, ByVal cellBounds As Rectangle, _
           ByVal rowIndex As Integer, _
           ByVal elementState As DataGridViewElementStates, _
           ByVal value As Object, ByVal formattedValue As Object, _
           ByVal errorText As String, _
           ByVal cellStyle As DataGridViewCellStyle, _
           ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _
           ByVal paintParts As DataGridViewPaintParts)
     
            ' The m_TwoColors  is disabled, so paint the border,  
            ' background as PositiveAndDefaultColor, and disabled button for the cell.
            If Not Me.TwoColors Then
     
                ' Draw the background of the cell, if specified.
                If (paintParts And DataGridViewPaintParts.Background) = _
                    DataGridViewPaintParts.Background Then
                    Dim cellBackground As New SolidBrush(PositiveAndDefaultColor)
                    graphics.FillRectangle(cellBackground, cellBounds)
                    cellBackground.Dispose()
                End If
     
                ' Draw the cell borders, if specified.
                If (paintParts And DataGridViewPaintParts.Border) = _
                    DataGridViewPaintParts.Border Then
     
                    PaintBorder(graphics, clipBounds, cellBounds, cellStyle, _
                        advancedBorderStyle)
                End If
     
                ' Calculate the area in which to draw TextBox.
                Dim textboxArea As Rectangle = cellBounds
                Dim textboxAdjustment As Rectangle = _
                    Me.BorderWidths(advancedBorderStyle)
                textboxArea.X += textboxAdjustment.X
                textboxArea.Y += textboxAdjustment.Y
                textboxArea.Height -= textboxAdjustment.Height
                textboxArea.Width -= textboxAdjustment.Width
     
                ' Draw the disabled TextBox text. 
                If TypeOf Me.FormattedValue Is String Then
                    TextRenderer.DrawText(graphics, CStr(Me.FormattedValue), _
                        Me.DataGridView.Font, textboxArea, SystemColors.GrayText)
                End If
     
     
            ElseIf Me.TwoColors Then ' The TwoColors cell is enabled
     
                ' Draw the background of the cell, if specified.
                If (paintParts And DataGridViewPaintParts.Background) = _
                    DataGridViewPaintParts.Background Then
                    Dim cellBackground As New SolidBrush(NegativeColor)
                    graphics.FillRectangle(cellBackground, cellBounds)
                    cellBackground.Dispose()
                End If
     
                ' Draw the cell borders, if specified.
                If (paintParts And DataGridViewPaintParts.Border) = _
                    DataGridViewPaintParts.Border Then
     
                    PaintBorder(graphics, clipBounds, cellBounds, cellStyle, _
                        advancedBorderStyle)
                End If
     
                ' Calculate the area in which to draw TextBox.
                Dim textboxArea As Rectangle = cellBounds
                Dim textboxAdjustment As Rectangle = _
                    Me.BorderWidths(advancedBorderStyle)
                textboxArea.X += textboxAdjustment.X
                textboxArea.Y += textboxAdjustment.Y
                textboxArea.Height -= textboxAdjustment.Height
                textboxArea.Width -= textboxAdjustment.Width
     
                ' Draw the enabled TextBox text. 
                If TypeOf Me.FormattedValue Is String Then
                    TextRenderer.DrawText(graphics, CStr(Me.FormattedValue), _
                        Me.DataGridView.Font, textboxArea, SystemColors.ControlText)
                End If
            Else
                ' The TwoColors cell is enabled, so let the base class 
                ' handle the painting.
                MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, _
                    elementState, value, formattedValue, errorText, _
                    cellStyle, advancedBorderStyle, paintParts)
            End If
        End Sub
    End Class
    lien MSDN ici:

    http://www.google.com/url?sa=t&sourc...E52aaWT8iHwk1g
    Bon code......

  4. #4
    Membre confirmé
    Homme Profil pro
    Inscrit en
    Mai 2010
    Messages
    132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Australie

    Informations professionnelles :
    Secteur : Bâtiment

    Informations forums :
    Inscription : Mai 2010
    Messages : 132
    Par défaut
    zebra crossing??... (recherche google) ... ah ouai quand même. Ben j'aimerai pouvoir me sentir si intelligent. T'en es?

    En tout cas merci à tous les deux, c'est le zebre mabrouki qui a vu juste:
    Les constructeurs de colonne et cell étaient bons mais il fallait "overrider" la fonction clone de la cell

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
        Public Overrides Function Clone() As Object
            Dim Cell As DGVProgressCell = CType(MyBase.Clone(), DGVProgressCell)
            Cell.TwoColors = Me.TwoColors
            Cell.NegativeColor = Me.NegativeColor
            Cell.PositiveAndDefaultColor = Me.PositiveAndDefaultColor
            Return Cell
        End Function
    c'est elle qui appelai le constructeur new() sans paramètre.

    Merci,
    Zebrette

  5. #5
    Membre confirmé
    Homme Profil pro
    Inscrit en
    Mai 2010
    Messages
    132
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Australie

    Informations professionnelles :
    Secteur : Bâtiment

    Informations forums :
    Inscription : Mai 2010
    Messages : 132
    Par défaut
    Après de nombreuses autres manipulations, et plusieurs custom datagridviewcolum /cell réussies, je conseillerais ceci:

    avoir un seul constructeur de datagridviewcell, et éventuellement plusieurs constructeur de datagridviewcolumn.

    Mais les propriétés custom communes à toutes les cellules sont ajoutées uniquement à la datagridviewcolumn, et c'est le paint event de la datagridviewcell qui lira les propriétés de la colonne en passant par datagridviewcell.OwningColumn...

    Attention aussi si vous voulez pouvoir changer les propriétés custom de vos colonnes pendant le design time, il faut overrid"er" la fonction Clone de la colonne.

    bonne réflexion,
    zebrette.

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

Discussions similaires

  1. Fonction Générique Constructeur Paramètre
    Par adrienfehr dans le forum C#
    Réponses: 6
    Dernier message: 14/02/2012, 07h23
  2. [POO] constructeurs, paramètres et héritage
    Par Belenos dans le forum Langage
    Réponses: 5
    Dernier message: 24/10/2009, 14h57
  3. Comment faire un constructeur paramétré ?
    Par Ishtar dans le forum Ada
    Réponses: 13
    Dernier message: 15/09/2009, 11h44
  4. Constructeur paramètre facultatifs
    Par Leole dans le forum C++
    Réponses: 3
    Dernier message: 29/11/2007, 20h51
  5. Réponses: 4
    Dernier message: 05/11/2007, 20h02

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