Question

How can we databind a datagridview to some of the My.Settings (user scoped) properties so the user can edit the values? This must be to a datagridview. I know we can bind to My.Settings in a form with textboxes and so on, but in this case we just want it as list of editable strings in a datagridview.

Of course some My.Settings entries can have different datatypes which complicates matters but generally we're only working with strings and booleans.

Also, let's assume the user understands that he must enter the string "true" to set a boolean to true. No checkbox column needed.


Here's what we are using (and it works), just looking for a better, leaner way:

here's the class:

Public Class MySettingsMaint

...

then we have a bindinglist (this is probably yuk):

Private list As BindingList(Of BindingKeyValuePair)

here's what the datagridview binds to:

Public ReadOnly Property DataSource() As Object 
    Get

        list = New BindingList(Of BindingKeyValuePair)
        list.Add(New BindingKeyValuePair("PhoneExtension", My.Settings.PhoneExtension.ToString.ToLower))
        list.Add(New BindingKeyValuePair("PhonePIN", My.Settings.PhonePIN.ToString.ToLower))
        list.Add(New BindingKeyValuePair("PhoneEnabled", My.Settings.PhoneEnabled.ToString.ToLower))
        Return From k In list Order By k.Key

        Return list
    End Get
End Property

...

Public Sub LoadGrid(ByVal grd As DataGridView) Implements 
/some stuff here to create two DataGridViewColumns
/one bound to Key, the other bound to Setting

End Sub

more yuk here, to save back to My.Settings:

Public Sub Save() Implements IMaintainable.Save
    My.Settings.PhoneExtension = (From x As BindingKeyValuePair In list Where x.Key = "PhoneExtension" Select x.Value.ToLower).ToList(0)
    My.Settings.PhonePIN = (From x As BindingKeyValuePair In list Where x.Key = "PhonePIN" Select x.Value.ToLower).ToList(0)
    My.Settings.PhoneEnabled = (From x As BindingKeyValuePair In list Where x.Key = "PhoneEnabled" Select x.Value.ToLower).ToList(0) = "true"

    My.Settings.Save()

End Sub

the private class required by the above class:

Private Class BindingKeyValuePair

    Sub New(ByVal k As String, ByVal v As String)
        Key = k
        Value = v
    End Sub

    Private _Key As String
    Public Property Key() As String
        /basic getsetter
    End Property


    Private _Value As String
    Public Property Value() As String
         /basic getsetter
    End Property


End Class
Was it helpful?

Solution

You should use the PropertyGrid control? It will help with regard to supporting richer property types.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top