Writing CSV file VB.NET - vb.net

i'm just having troubles with a CSV file saving code in VB.NET
I'm trying to save a CSV file that will be read in a DataGridView. I just made the "reading" code, it works perfectly! What's wrong with saving of the file?
Public Class Builder
Sub Create_Records()
Dim i As Integer
For i = 0 To Manager.Grid.Rows.Count - 1
Manager.Grid.Rows.Add("ciao;", "comestai")
Next
End Sub
Sub Write()
If (Not System.IO.Directory.Exists("C:\MyPCBuilder")) Then
System.IO.Directory.CreateDirectory("C:\MyPCBuilder")
End If
Dim Write As New System.IO.StreamWriter("C:\MyPCBuilder\builds.csv")
For i = 0 To Manager.Grid.Rows.Count - 1
Text = ""
For j = 0 To 1
If Text = Text & Manager.Grid.Rows(i).Cells(j).Value & ";" Then
Else
Text = Text & Manager.Grid.Rows(i).Cells(j).Value
End If
Next
Write.WriteLine(Text)
Next
Write.Close()
End Sub
Private Sub btn_Confirm_Click(sender As Object, e As EventArgs) Handles btn_Confirm.Click
Create_Records()
Write()
End Sub
End Class

The If-statement in your inner loop is wrong. The Then part is empty and the condition is strange. Since you have only 2 columns, simply write
For i = 0 To Manager.Grid.Rows.Count - 1
Text = Manager.Grid.Rows(i).Cells(0).Value & ";" & Manager.Grid.Rows(i).Cells(1).Value
Write.WriteLine(Text)
Next
If you want to keep this inner loop (in case you have more columns or a variable number of columns), test for the index instead (outer loop not shown)
Text = ""
For j = 0 To 1
If j > 0 Then
Text = Text & ";"
End If
Text = Text & Manager.Grid.Rows(i).Cells(j).Value
Next

Related

Get focus on unbound textbox when form returns no records

I'm a little stumped.
I've got an MS Access front end application for an SQL Server back end. I have an orders form with a list box that, when selected and a "Notes" button is clicked will open another form of notes. This is a continuous form and has a data source (linked table - a view) from the back end database.
When the notes button is clicked in the main orders form, it passes a filter and an OpenArgs string to the Notes form in this code:
Private Sub cmdItemNotes_Click()
Dim i As Integer
Dim ordLine As Boolean
Dim line As Integer
Dim args As String
If Me.lstOrders.ItemsSelected.count = 1 Then
ordLine = False
With Me.lstOrders
For i = 0 To .ListCount - 1
If .selected(i) Then
If .Column(16, i) = "Orders" Then
ordLine = True
line = .Column(0, i)
End If
End If
Next i
End With
If ordLine Then
args = "txtLineID|" & line & "|txtCurrentUser|" & DLookup("[User]", "tblUsers", "[Current] = -1") & "|txtSortNum|" & _
Nz(DMax("[SortNum]", "dbo_vwInvoiceItemNotesAll", "[LineID] = " & line), 0) + 1 & "|"
DoCmd.OpenForm "frmInvoiceItemNotes", , , "LineID = " & line, , , args
Else
'Potting order notes
End If
Else: MsgBox "Please select one item for notes."
End If
Here is my On Load code for the Notes form:
Private Sub Form_Load()
Dim numPipes As Integer
Dim ArgStr As String
Dim ctl As control
Dim ctlNam As String
Dim val As String
Dim i As Integer
ArgStr = Me.OpenArgs
numPipes = Len(ArgStr) - Len(Replace(ArgStr, "|", ""))
For i = 1 To (numPipes / 2)
ctlNam = Left(ArgStr, InStr(ArgStr, "|") - 1)
Set ctl = Me.Controls(ctlNam)
ArgStr = Right(ArgStr, Len(ArgStr) - (Len(ctlNam) + 1))
val = Left(ArgStr, InStr(ArgStr, "|") - 1)
ctl.Value = val
ArgStr = Right(ArgStr, Len(ArgStr) - (Len(val) + 1))
Next i
End Sub
This code executes fine. The form gets filtered to only see the records (notes) for the line selected back in the orders form.
Because this is editing a table in the back end, I use stored procedures in a pass through query to update the table, not bound controls. The bound controls in the continuous form are for displaying current records only. So... I have an unbound textbox (txtNewNote) in the footer of the form to type a new note, edit an existing note, or post a reply to an existing note.
As stated above, the form filters on load. Everything works great when records show. But when it filters to no records, the txtNewNote textbox behaves quite differently. For instance, I have a combo box to mention other users. Here is the code after update for the combo box:
Private Sub cmbMention_AfterUpdate()
Dim ment As String
If Me.txtNewNote = Mid(Me.txtNewNote.DefaultValue, 2, Len(Me.txtNewNote.DefaultValue) - 2) Then
Me.txtNewNote.Value = ""
End If
If Not IsNull(Me.cmbMention) Then
ment = " #" & Me.cmbMention & " "
If Not InStr(Me.txtNewNote, ment) > 0 Then
Me.txtNewNote = Me.txtNewNote & ment
End If
End If
With Me.txtNewNote
.SetFocus
.SelStart = Len(Nz(Me.txtNewNote, ""))
End With
End Sub
The problem occurs with the line
.SelStart = Len(Nz(Me.txtNewNote, ""))
When there are records to display, it works. When there are no records to display, it throws the Run-time error 2185 "You can't reference a property or method for a control unless the control has the focus."
Ironically, if I omit this line and make the .SetFocus the last line of code in the sub, the control is in focus with the entire text highlighted.
Why would an unbound textbox behave this way just because the filter does not show records?
Thanks!

How can I get the value of a text variable that have the same name of a integer variable in VBA?

I have an userform that get some values..and I try to use a loop to get the values of theses variables that I get through a textbox, so I try to get the value of a variable through other variable(text) that have the same name of a number variable.. Anyone can help me to do this?
Example of my variables are: amountfra11a,amountfra12a...(these are the name of my textbox)
follows the code:
Private Sub OKTESTE_Click()
Dim b As Integer
For i = 1 To 1
a = "amountfra1" & i & "a.value"
b = CInt(a)
If b = 10 Then
c = d
End If
Next
End Sub
You can get the texbox values via the Controls collection of the UserForm:
Private Sub OKTESTE_Click()
Dim i, nm, a
For i = 11 To 12 'for example
nm = "amountfra" & i & "a"
a = Me.Controls(nm).Text
MsgBox nm & " = " & a
Next
End Sub

VB Reading a text file into a 2D array?

I am trying to create a sudoku game, with load and save game functions in VB and I was wondering how it would be possible to load a save file(the numbers on the sudoku board and time score) and make the numbers within the file correspond to their exact location on the new board. For saving the file I have this:
Private Sub saveBoard(fileName As String)
Dim f As StreamWriter = New StreamWriter(fileName)
For col = 0 To 8
Dim sudokuLine = ""
For row = 0 To 8
If (board(row, col).Text = "") Then
sudokuLine += "0"
Else : sudokuLine += board(row, col).Text
End If
sudokuLine += " "
Next
f.WriteLine(sudokuLine)
Next
f.WriteLine(lblMinutes.Text + " " + lblSeconds.Text)
f.Close()
End Sub
Also I know about StreamReader...
This could be the loadBoard that corresponds to your saveBoard.
Of course a bit of testing is required here and a more fool proof approach to handle critical errors (like a different file passed as input) .
Notice that I have added the using statement around the opening of the Stream. This should be done also in the saveBoard above to avoid problems with files locked in case of exceptions.
Private Sub loadBoard(fileName As String)
Using f = New StreamReader(fileName)
For col = 0 To 8
Dim sudokuColumn = f.ReadLine()
Dim cells() = sudokuColum.Split()
For row = 0 To 8
If cells(row, col) = "0") Then
boards(row, col).Text = ""
Else
board(row, col).Text = cells(row,col)
End If
Next
Next
lblMinutes.Text = f.ReadLine()
End Using
End Sub

How to remove vb.net Richtextbox lines that not contains specific text?

I use the next code to remove lines from Richtextboxes but that way i can only tell what line to remove. I need to remove all lines that not contains specific text, can this be done with some edits of my code?
1st piece:
Private Property lineToBeRemovedlineToBeRemoved As Integer
2nd piece:
Dim lineToBeRemoved As Integer = 0
lineToBeRemovedlineToBeRemoved = lineToBeRemoved - 0
Dim str As String = RichTextBox1.Lines(lineToBeRemoved)
RichTextBox1.Find(str & vbCr)
RichTextBox1.SelectedText = ""
This code will remove any line from a richtextbox RichTextbox1 that does not contain "Test" on it. Remember to add Imports System.Text.RegularExpressions to the top of your code.
Private Sub RemoveLines()
Dim lines As New List(Of String)
lines = RichTextBox1.Lines.ToList
Dim FilterText = "Test"
For i As Integer = lines.Count - 1 To 0 Step -1
If Not Regex.IsMatch(lines(i), FilterText) Then
lines.RemoveAt(i)
End If
Next
RichTextBox1.Lines = lines.ToArray
End Sub
You code is not close. You should start over. Use a for loop to go through the RichTextBox lines. If the text is not in a line, then delete it. Tip: It may be easier to go from the last line to the first to avoid problems when deleting.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RTB.Select(RTB.GetFirstCharIndexFromLine(2), RTB.Lines(2).Count)
RTB.SelectionLength = RTB.Lines(2).Length + 1
RTB.SelectedText = ""
End Sub
Try this code, I applied to my prog and it work good.
When use, just ... call dels("unwanted") ==> Line which contain unwanted word will disappear.
Private Sub dels(sw As String)
Dim ud As String = "" 'for keep all we need
Dim cn As Integer = 0 'for avoid empty line
For Each line As String In RichTextBox1.Lines 'for every line in reichtextbox
If Len(line) > 5 Then 'if that line got more than 5 character
If InStr(line.ToLower, sw.ToLower) < 1 Then 'transform them to lower case for better resulted
If cn = 1 Then ud = ud + vbCrLf 'not place new-line if it is first
ud = ud + line 'keep this line if not match ne want delete
cn = 1 'turn-off first line signal
End If
End If
Next
RichTextBox1.Clear() 'empty richtextbox
RichTextBox1.AppendText(ud) 'update richtextbox with the unwanted
End Sub

Why does Microsoft Visual Basic skip over part of this code

I'm trying to make some labels on my Form to be visible, but i don't want to use a lot of if statements, but for some reason whenever i put Me.Controls(lbl).Visbel = True in a for or do loop it skips the whole loop. The code worked perfectly the way I wanted it until i got an error for calling Dim lbl = Controls("Label" & counter_3) for the whole class instead of in the From_load private sub. Sometimes i can get it to work, but only one label is visible
Dim chararray() As Char = word_list(random_word).ToCharArray
Dim lbl = "Label" & counter_3
For Each item In chararray
If item = Nothing Then
Else
word_list(counter_2) = item.ToString()
counter_2 += 1
End If
Next
For Each item In chararray
If item = Nothing Then
Else
counter_3 += 1
Me.Controls(lbl).Visible = True
MsgBox(item & " " & counter_3)
End If
Next
I've also tried. In both the loops are completely skipped over. I know this because the MsgBox's don't appear.
Dim chararray() As Char = word_list(random_word).ToCharArray
Dim lbl = Controls("Label" & counter_3)
For Each item In chararray
If item = Nothing Then
Else
word_list(counter_2) = item.ToString()
counter_2 += 1
End If
Next
For Each item In chararray
If item = Nothing Then
Else
counter_3 += 1
lbl.Visble = True
MsgBox(item & " " & counter_3)
End If
Next
The thing that I am noticing is that you are creating a Char array based on a random word returned from your word_list, you then iterate through the Char array using the count of the character in the array as an index into your word_list, if the amount of characters in your word exceeds the amount of words in your list you will get an error and since this error is in the Forms Load event it will be swallowed and all the code after it will be aborted. There are also other issues that I would change like making sure all declarations have a type and I would probably use the Controls.Find Method instead and check that it has an actual object. But what I would probably do first is move your code to a separate Subroutine and call it after your IntializeComponent call in the Forms Constructor(New) Method.
Something like this.
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
YourMethod
End Sub
Public Sub YourMethod()
Dim chararray() As Char = word_list(random_word).ToCharArray
Dim lbl As Control() = Controls.Find("Label" & counter_3, True)
For Each item In chararray
If item = Nothing Then
Else
word_list(counter_2) = item.ToString()
counter_2 += 1
End If
Next
For Each item In chararray
If item = Nothing Then
Else
counter_3 += 1
If lbl.Length > 0 Then
lbl(0).Visible = True
Else
MsgBox("Control not Found")
End If
MsgBox(item & " " & counter_3)
End If
Next
End Sub