Hi all,

I'm a VB newbie in this respect so please be patient with me! I have an app that requires the user to input a bunch of values for various things in textboxes, datagridviews and propertygrids. I want this user input to be written to a text file in a specific format (say, on the click of a button, but dynamic writing wouldn't be so bad!)

What is the best way to do this? I'm thinking using a dataset, but I'm no expert so a bit of advice would be helpful.

Cheers

Dani AI

Generated

Building on 's suggestion to label sections and 's delimited-file example, this focuses on reliably exporting PropertyGrid contents. PropertyGrid shows an object (or SelectedObjects) — use TypeDescriptor.GetProperties rather than raw reflection so the exporter respects Browsable and TypeConverter behavior. The recommended output is headered sections like [PropertyGridName] followed by flattened key=value lines; that format is simple for a text-based consumer and easy to debug.

Imports System.ComponentModel
Imports System.Globalization
Imports System.Text
Imports System.IO

Private Sub ExportPropertyGrid(pg As PropertyGrid, filePath As String)
    Dim sb As New StringBuilder()
    Dim objs = If(pg.SelectedObjects, New Object() {pg.SelectedObject})
    For i As Integer = 0 To objs.Length - 1
        Dim header = "[" & pg.Name & If(objs.Length > 1, "_" & i.ToString(), "") & "]"
        sb.AppendLine(header)
        ExportObject(objs(i), sb, "", 0)
        sb.AppendLine()
    Next
    File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8)
End Sub

Private Sub ExportObject(obj As Object, sb As StringBuilder, prefix As String, depth As Integer)
    If obj Is Nothing Then
        sb.AppendLine((If(prefix = "", "Value", prefix)) & "=")
        Return
    End If
    If depth > 6 Then
        sb.AppendLine(prefix & "=<max depth>")
        Return
    End If
    Dim props = TypeDescriptor.GetProperties(obj)
    For Each pd As PropertyDescriptor In props
        If Not pd.IsBrowsable Then Continue For
        Dim name = If(String.IsNullOrEmpty(prefix), pd.Name, prefix & "." & pd.Name)
        Dim val = pd.GetValue(obj)
        If val Is Nothing OrElse TypeOf val Is String OrElse TypeOf val Is ValueType Then
            sb.AppendLine(name & "=" & EscapeValue(Convert.ToString(val, CultureInfo.InvariantCulture)))
        Else
            ExportObject(val, sb, name, depth + 1)
        End If
    Next
End Sub

Private Function EscapeValue(s As String) As String
    If s Is Nothing Then Return ""
    Return s.Replace(vbCrLf, "\n").Replace("=", "\=").Replace("[", "\[").Replace("]", "\]")
End Function

Notes and troubleshooting: use InvariantCulture when serializing numbers/dates so the consumer gets consistent formatting; respect Browsable=false (TypeDescriptor does that); protect against deep recursion with a depth limit or visited set; if the external program needs exact field names/order, supply a mapping layer (dictionary or a small custom ExportName attribute) to translate property names before writing. If control of both sides is possible, JSON or XML will be more robust than bespoke text; otherwise the header + key=value approach is pragmatic and easy to validate.

Recommended Answers

All 3 Replies

So many data into a text file? Is this a smart way to do it? How will you then know what is what?
You can use flags like some special characters that the code can recognize them as NOT-TEXT, but like: this is from button1, this is from datagridview, and so on. You can put this into square brackets: [textBox1], or [datagridview1],...

To get all data to be written into text file would be best to use StringBuilder class, and append all to it from all controls.
From textboxes its simple to get Text, from dataGridView (dgv) its a bit harder. I assume your dgv is already bound to some data source (like dataset, or datatable) so you can loop through rows of dataTable and create a stirng from each row (if its not bound you can do the same with looping through dgv it self).

Can you handle this?

I have done this thing...chec below if it helps u

'Path1 is a string variable declared globally


 Dim di As DirectoryInfo = New DirectoryInfo(Application.StartupPath & "\Images\" + patientname + Date.Today.ToString("yyyy.MM.dd")) --- checked if a directory exists
 If Not di.Exists Then 'if no create the directory
     di.Create()
     Dim fileLoc As String = Application.StartupPath & "\Images\" + patientname + Date.Today.ToString("yyyy.MM.dd") + "\PatientRegEntry.txt"
     FileOpen(1, fileLoc, OpenMode.Output)
     Path1 = txtPatientID.Text + "*" + patientname + "*" + txtFName.Text + "*" + MName + "*" + LName + "*" + Age + "*" + Gender + "*" + Address + "*" + PhoneNo + "*" + MobNo + "*" + ReasonCurr + "*" + DenHist + "*" + DOB + "*" + ImagePath + "*" + DocName
     Print(1, Path1)
     FileClose()
End If

Mitja,

It has to be a text file because another program I use at work will read the text file and do an analysis. Also, I can handle writing the data from text boxes and DGVs (in fact, I've done it already), but I have a number of customised PropertyGrids, and writing the data from these is proving to be difficult.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.