Home > Mobile >  How to save checkbox value in xml using vb.net
How to save checkbox value in xml using vb.net

Time:08-25

I know, maybe this is a question that comes up quite often, but I haven't been able to work on it. How can I save this checkbox values in an XML file using VB.Net ?

 Private Sub ChkVul_Click(sender As Object, e As EventArgs) Handles ChkVul.Click
    If ChkVul.Checked = True Then
        Me.pnlInsert.Visible = True
    Else
        Me.pnlInsert.Visible = False
    End If
End Sub

CodePudding user response:

Before I provide you with an answer, I wanted to recommend a slight code change. Since you are setting the Boolean value of pnlInsert.Visible based on a condition, which itself returns a Boolean value, simply get rid of the conditional check in the first place:

pnlInsert.Visible = ChkVul.Checked

Now to your question. What you are essentially asking is how to write a value to an XML file. Something to consider is that XML is only a markup language. At the end of the day, an XML file is simply a file that contains formatted text.

If you do not already have an XML file to read from, simply create a new instance of a XDocument (documentation). If you do have an XML file, then create a new instance of a XDocument by calling the static XDocument.Load method (documentation). Here is a function that takes in a file location and attempts to load a XDocument, if it is unable to then it returns a blank XDocument with a single <root> element:

Private Function LoadOrCreateXml(filename As String) As XDocument
    Dim document = New XDocument()
    document.Add(New XElement("root"))

    Try
        If (Not String.IsNullOrWhiteSpace(filename) AndAlso IO.File.Exists(filename)) Then
            document = XDocument.Load(filename)
        End If
    Catch ex As Exception
        ' for the sake of this example, just silently fail
    End Try

    Return document
End Function

Now that you have an XDocument, it is just a matter of writing the value. You did not provide any details as to where the value should go or what the tag name should be, so I am going to assume that it should be a child of the <root /> element and the value would look something like this: <ChkVul>true/false</ChkVul>.

To do this, we will need to get the <root /> element by calling the Element method (documentation) on the XDocument to get the element and then call the Add method (documentation) on the resulting XElement to add our node with the value:

Dim document = LoadOrCreateXml("my-xml-file.txt")
document.Element("root").Add(New XElement("ChkVul", ChkVul.Checked))

The final piece of all this is to write the in-memory XDocument back to the file. You can leverage the XDocument.Save method (documentation):

Dim filename = "my-xml-file.txt"
Dim document = LoadOrCreateXml(filename)
document.Element("root").Add(New XElement("ChkVul", ChkVul.Checked))
document.Save(filename)

CodePudding user response:

Maybe this is what you have in mind. I tested this with other controls,

Public Class Form1

    Private SavePath As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                                                  "MyControls.xml") 'some valid path <-----------<<<

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        SaveCheckedState(ChkVul, "ChkVul", True)
    End Sub

    Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If IO.File.Exists(SavePath) Then
            Try
                MyControls = XElement.Load(SavePath)
                For Each el As XElement In MyControls.Elements
                    Dim ctrl() As Control = Me.Controls.Find(el.@name, True)
                    If ctrl.Length > 0 Then
                        Dim chkd As System.Reflection.PropertyInfo = ctrl(0).GetType().GetProperty("Checked")
                        Dim chkdV As Boolean = Boolean.Parse(el.@checked)
                        chkd.SetValue(ctrl(0), chkdV)
                    End If
                Next
            Catch ex As Exception
                'todo
            End Try
        End If
    End Sub

    Private Sub ChkVul_CheckedChanged(sender As Object, e As EventArgs) Handles ChkVul.CheckedChanged
        If ChkVul.Checked Then
            Me.pnlInsert.Visible = True
        Else
            Me.pnlInsert.Visible = False
        End If
        SaveCheckedState(ChkVul, "ChkVul")
    End Sub

    Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
        SaveCheckedState(RadioButton1, "RadioButton1")
    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        SaveCheckedState(CheckBox1, "CheckBox1")
    End Sub

    Private MyControls As XElement = <controls>
                                     </controls>

    Private Sub SaveCheckedState(Ctrl As Control,
                                 Name As String,
                                 Optional Save As Boolean = False)

        If Ctrl.GetType().GetProperty("Checked") IsNot Nothing Then
            Dim chkd As System.Reflection.PropertyInfo = Ctrl.GetType().GetProperty("Checked")
            Dim chkdV As Boolean = CBool(chkd.GetValue(Ctrl))
            Dim ie As IEnumerable(Of XElement)
            ie = From el In MyControls.Elements
                    Where el.@name = Ctrl.Name
                    Select el Take 1

            Dim thisXML As XElement
            If ie.Count = 0 Then
                thisXML = <ctrl name=<%= Name %>></ctrl>
                MyControls.Add(thisXML)
            Else
                thisXML = ie(0)
            End If
            thisXML.@checked = chkdV.ToString
        End If
        If Save Then
            Try
                MyControls.Save(SavePath)
            Catch ex As Exception
                'todo
                ' Stop
            End Try
        End If
    End Sub
End Class
  • Related