Link to home
Create AccountLog in
Visual Basic.NET

Visual Basic.NET

--

Questions

--

Followers

Top Experts

Avatar of Kevin
Kevin🇺🇸

VB.NET Complex Code to output to a file
Good Afternoon,

To be honest I just started playing with Visual Studio Express 2012 last night, so my knowledge on the VB.Net language as well as VB in general is on a very thin beginner level.

Please do not recommend alternatives to VB .Net as I would like to continue using this language for my present program.

Basically the program will be used to output what the user selects to a file.

I need some help with outputting the information to the file.

Below, is a screenshot of the form to get an idea.

User generated image
So what I need to happen is this:

1. The user will browse for a “folder”.

Within the selected folder will be a few 100 files all having different file names. The file names will all have an account number in them. So an example of what the files will look like are below:

63255 – People HWU Oct 2012 – Final Steve Markesu.pdf
4872345 – People WOOPW Oct 2012 – Final Maria Menez.pdf
October 2012 Harry Towner Acct09839.pdf
Peters Plumbing Acc4940523 Oct 2012.docx

2. The user will then select a filing date.

3. The user will then select an area from the datagrid box. This datagrid box is linked to a sql database table.

4. The user will then push the “File To System” button (button3).

When that button is pushed the program will output what the user selected to the “C:\Indexbatch<date and time stamp of when this file is created>.sdd1” file.

Contents of the output file must be similar to the below examples:

 
H:\test\test2\test3\test4\test5\63255 – People HWU Oct 2012 – Final Steve Markesu.pdf|63255|63255||Documentation|Client Documentation|Bill Payment Agreement||10/09/2012|
H:\test\test2\test3\test4\test5\4872345 – People WOOPW Oct 2012 – Final Maria Menez.pdf|4872345|4872345||Documentation|Client Documentation|Bill Payment Agreement||10/09/2012| 
H:\test\test2\test3\test4\test5\October 2012 Harry Towner Acct09839.pdf|09839|09839||Documentation|Client Documentation|Bill Payment Agreement||10/09/2012|
H:\test\test2\test3\test4\test5\ Peters Plumbing Acc4940523 Oct 2012.docx|4940523|4940523||Documentation|Client Documentation|Bill Payment Agreement||10/09/2012|

Open in new window


So the first part of the output is the folder location that the user selected as well as the file name of the file within that directory.

H:\test\test2\test3\test4\test5\63255 – People HWU Oct 2012 – Final Steve Markesu.pdf

Next is the account number that was read from the file name. The account number is between 5 and 10 numbers. So the program must look for a 5 to 10 digit number (no spaces or dots etc) from within the file name and place it in the output file twice and separated by the | as seen below.

|63255|63255||

Next is what was selected in the grid from the DocGroup, DocType and DocSubType columns

Documentation|Client Documentation|Bill Payment Agreement

Lastly is the date that the user selected being MM/DD/YYYY

||10/09/2012|

Below is the code I have so far, it’s nothing really.

 

Public Class UserForm

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            TextBox1.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

    Private Sub UserForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the ' TRWBlancheDataSet.DocTypeList_TRW ' table. You can move, or remove it, as needed.
        Me.DocTypeList_TRWTableAdapter.Fill(Me.TRWBlancheDataSet.DocTypeList_TRW)

    End Sub

    Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)

    End Sub

    Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        
    End Sub
    
    Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged

    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

    End Sub
End Class

Open in new window


Can anyone make this work? Do let me know if you have any questions.

Regards,
N

Zero AI Policy

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Bob LearnedBob Learned🇺🇸

So much information that I am not sure what you are asking for...

Avatar of KevinKevin🇺🇸

ASKER

I figured it was a lot of info :( .

I've been experimenting with this since yesterday and have gotten a little farther. I had no idea how to output the information to a file and have managed to get a little bit of it with the code below:

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim objWriter As New System.IO.StreamWriter("C:\Users\jdoe\Desktop\Advices\output\output.txt", False)
        objWriter.WriteLine(TextBox1.Text & "|" & DateTimePicker1.Text)
        objWriter.Close()

    End Sub

Open in new window


Essentially all i want to do is export all of the values the user selected on the design form in to a text file.

The above codes outputs the below line to the text file:

H:\test\test1\test2\test3\|4/25/2013

Open in new window


I now need to know how to get this code to output:

1.  The file names from within the directory the user chose from the textbox.
2. The code to read the account number from within the filename and place it in the string of output.
3. The code to read what the user selected from the datagridview box and place it in the string of output.
4. The date to be formatted as MM/DD/YYYY in the strings output instead of M/D/YYYY

So final result would look like this:

H:\test\test2\test3\test4\test5\63255 – People HWU Oct 2012 – Final Steve Markesu.pdf|63255|63255||Documentation|Client Documentation|Bill Payment Agreement||10/09/2012|

Open in new window


Does this information help out any?

Avatar of Bob LearnedBob Learned🇺🇸

There is a 1-line statement to write file text:

     System.IO.File.WriteAllText(path, content)

Shortened to this with an Imports System.IO:

     File.WriteAllText(path, content)

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of KevinKevin🇺🇸

ASKER

Bill Prew (another EE Expert) was able to help me accomplish a similar idea but for something else using a vbs script.

I've looked at this but can't make heads or tails of it since i dont know VB. The end result after running this code is the end result i want to happen with my vb.net project being the information in the output file.

This is a little different as the information in the datagrid is already in the vbs file as

"||Operations|Correspondence|Valuation||"

This is different from what i am trying to accomplish now Bill codes has this information already predefined in the vbs script. With this VB.net project i need the user to select this information from the datagrid and it will end up in the output file.

Does this make more sence?

' Define useful constants
Const ForWriting = 2
Const cBasePath = "\\ServerA\FolderA\FolderB\FolderC\"
Const cBaseExt = ".pdf"

' See if command line contained parms, else prompt for them
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oArgs = WScript.Arguments
If oArgs.Count = 2 Then
   sParmDate = oArgs(0)
   sParmFile = oArgs(1)
Else
   sParmDate = DoPrompt("Please enter date (DD-MMM-YY): ")
   sParmFile = DoPrompt("Please enter output file (C:\TRWmmmYYYY.trw):")
End If

' Convert string date
dParmDate = CDate(sParmDate)
sDate = Day(dParmDate) & "-" & UCase(MonthName(Month(dParmDate), True)) & "-" & Right(Year(dParmDate), 2)

' Open output file
Set oOutput = oFSO.OpenTextFile(sParmFile, ForWriting, True)

' Find files in folder matching select criteria and process
Set oFolder = oFSO.GetFolder(cBasePath & sDate)
For Each oFile In oFolder.Files
   If LCase(Right(oFile.Name, Len(cBaseExt))) = LCase(cBaseExt) Then
      ProcessFile oFile
   End If
Next

' Done
oOutput.Close
Wscript.Quit

' Format and write this file to output file
Sub ProcessFile (oFile)
   aParse = Split(oFile.Name, ".")
   sOutput = cBasePath & sDate & "\" & oFile.Name & "|" & aParse(3) & "|" & aParse(3) & "||Operations|Correspondence|Valuation||" & Right("0" & Month(dParmDate), 2) & "/" & Right("0" & Day(dParmDate), 2) & "/" & Year(dParmDate) & "|"
   oOutput.WriteLine sOutput
End Sub

' User input prompt function
Function DoPrompt (sPrompt)
   ' Check if the script runs in CSCRIPT.EXE
   If UCase(Right(WScript.FullName, 12)) = "\CSCRIPT.EXE" Then
      ' If so, use StdIn and StdOut
      WScript.StdOut.Write sPrompt & " "
      DoPrompt = WScript.StdIn.ReadLine
   Else
      ' If not, use InputBox( )
      DoPrompt = InputBox(sPrompt)
   End If
End Function

Open in new window


Avatar of Bob LearnedBob Learned🇺🇸

There is a lot going on in these questions:

1.  The file names from within the directory the user chose from the textbox.
2. The code to read the account number from within the filename and place it in the string of output.
3. The code to read what the user selected from the datagridview box and place it in the string of output.
4. The date to be formatted as MM/DD/YYYY in the strings output instead of M/D/YYYY


If these are all inter-related, then this should be easy, but if not, then we have the possibility of a never-ending question, and that is something that I am not prepared to tackle now.

For #4, if you have a Date variable, then you can use the Date.ToString("format") to format the date.

Example:

Dim dateTime As String = Now.ToString("dd MMM yyyy")

Open in new window


Avatar of KevinKevin🇺🇸

ASKER

Yes they are all inter-related. Im sure it is very easy to do I just dont know the programming language so don't know where to start. But i have gotten the date and folder path as you saw in my results above.

Thanks for the date, I also found the code to make this possible being below:

Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
        ' Set the Format type and the CustomFormat string.
        DateTimePicker1.Format = DateTimePickerFormat.Custom
        DateTimePicker1.CustomFormat = "MM/dd/yyyy"
    End Sub

Open in new window


With this question:

3. The code to read what the user selected from the datagridview box and place it in the string of output.

I've found this posting on stackoverflow.

http://stackoverflow.com/questions/724146/get-text-from-datagridview-selected-cells

This guy is trying to get the text selected from within his datagridview to a text box. What I am looking for is similar I am just trying to get this text to the output file within that same line with the date, path etc. And I want the data sperated by |'s

So final result will look like this within the line for question 3.

Documentation|Client Documentation|Bill Payment Agreement

Open in new window


Do let me know if you are clear on my question # 3.

If you are still not  to make sense with what I am trying to accomplish, no worries I will just post my questions on a programming forum.

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


Avatar of Bob LearnedBob Learned🇺🇸

You can references cells in the DataGridView by {column, row}, as in:

Dim value As String = Me.DataGridView1(1,1).Value.ToString()

Open in new window


This code uses the Item property, which is a default property (or indexer), that you can reference without the full name.  The equivalent would be:

Dim value As String = Me.DataGridView1.Item(1,1).Value.ToString()

Open in new window


Avatar of KevinKevin🇺🇸

ASKER

Ok so how would I make it appear in the output file?

This doesnt work:


 Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        Dim value As String = Me.DataGridView1.Item(1, 1).Value.ToString()

    End Sub

Open in new window


 Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim objWriter As New System.IO.StreamWriter("C:\jdoe\output\output.txt", False)
        objWriter.WriteLine(TextBox1.Text & "|" & DateTimePicker1.Text & "|" & DataGridView1.Text)
        objWriter.Close()

    End Sub

Open in new window


I just recieve this result in the output file when button3 is clicked.

C:\Users\jdoe\output|4/25/2013|

Avatar of Bob LearnedBob Learned🇺🇸

I don't understand what is not working, if you have output in your file...

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.


Avatar of KevinKevin🇺🇸

ASKER

Shouldn't something need to go on line 3 for it?

I put "DataGridView1.Text" is that correct?

 Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim objWriter As New System.IO.StreamWriter("C:\jdoe\output\output.txt", False)
        objWriter.WriteLine(TextBox1.Text & "|" & DateTimePicker1.Text & "|" & DataGridView1.Text)
        objWriter.Close()

    End Sub

Open in new window


Avatar of Bob LearnedBob Learned🇺🇸

You need to reference content in a cell, not the Text property.

Avatar of KevinKevin🇺🇸

ASKER

Morning TheLearnedOne,

As I mentioned before I do not know VB nor VB.Net.

Can you please provide me with an example as to what you mean by:

You need to reference content in a cell, not the Text property.

Kind Regards,
N

Free T-shirt

Get a FREE t-shirt when you ask your first question.

We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads.


ASKER CERTIFIED SOLUTION
Avatar of Nasir RazzaqNasir Razzaq🇬🇧

Link to home
membership
Log in or create a free account to see answer.
Signing up is free and takes 30 seconds. No credit card required.
Create Account

Avatar of KevinKevin🇺🇸

ASKER

Thank you CodeCruiser.

Your code definetly pushed me up the ladder a little more.

Though the system doesnt understand the "txtdirectory" nor the "txtDate" is your code VB.net?

I managed to use some of your code regarding the DataGridView to get sucessful results with the below code.

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim objWriter As New System.IO.StreamWriter("C:\output\output.txt", False)
        objWriter.WriteLine(TextBox1.Text & "||" & DataGridView1.SelectedRows(0).Cells(0).Value & "|" & DataGridView1.SelectedRows(0).Cells(1).Value & "|" & DataGridView1.SelectedRows(0).Cells(2).Value & "||" & DateTimePicker1.Text & "|")
        objWriter.Close()

    End Sub
End Class

Open in new window


Which works beautifully. Results when run below:

C:\Marketing\Clients||Documentation|Client Documentation|Address Change||04/09/2013|

Open in new window


So you have solved my problem of getting the selected values from the datagridview.

Can you help me now with getting the file names within the directory chosen from button1
(code below), in that output line as well. Which i think you tried already from your code above but its not working, you did say it was untested.

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            TextBox1.Text = FolderBrowserDialog1.SelectedPath
        End If
    End Sub

Open in new window


Thanks,
N

Avatar of Nasir RazzaqNasir Razzaq🇬🇧

txtDirectory is the name of the textbox where user puts the directory so you have to replace it with the name that you are using. Similarly, txtDate is the date selection drop down.

Avatar of KevinKevin🇺🇸

ASKER

Thank you very much Code Cruiser.

Reward 1Reward 2Reward 3Reward 4Reward 5Reward 6

EARN REWARDS FOR ASKING, ANSWERING, AND MORE.

Earn free swag for participating on the platform.

Visual Basic.NET

Visual Basic.NET

--

Questions

--

Followers

Top Experts

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to Visual Basic pre-2002, it is not the same technology,