Insert custom text on datagridview row export to TXT - vb.net

For the code below, I want to put at the beginning of each line exported in TXT the following text : "S,1,___,,;" + the row exported from database.
How can I add for each line that text on export? For the moment I have the text only on the firs line ( check pictures attached)
If DataGridView1.RowCount = 0 Then
MessageBox.Show("Lista este goala")
Else
If Directory.Exists("C:\test") = False Then
Directory.CreateDirectory("C:\test")
End If
Dim sFile As String = "C:\test\test.txt"
If File.Exists(sFile) = True Then
My.Computer.FileSystem.DeleteFile(sFile,
FileIO.UIOption.OnlyErrorDialogs,
FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.DoNothing)
End If
Using f As New IO.StreamWriter(sFile, True)
Dim col As String = ""
Dim a As String = "S,1,______,_,__;"
Dim row As String = ""
Dim i As Integer = 0
For Each r As DataGridViewRow In DataGridView1.Rows
For Each c As DataGridViewColumn In DataGridView1.Columns
row = row & Convert.ToString(r.Cells(c.HeaderText).Value) & ";"
Next
If i < DataGridView1.Rows.Count - 1 Then row &= Environment.NewLine
Next
f.WriteLine(a & row)
End Using
Using f2 As New IO.StreamWriter(sFile, True)
Dim col As String = ""
Dim row As String = ""
Dim i As Integer = 0
For Each r As DataGridViewRow In DataGridView3.Rows
For Each c As DataGridViewColumn In DataGridView3.Columns
row = row & Convert.ToString(r.Cells(c.HeaderText).Value) & ";"
Next
If i < DataGridView3.Rows.Count - 1 Then Row &= Environment.NewLine
Next
f2.WriteLine("T,1,______,_,__;" & row)
f2.Close()
MessageBox.Show("Bon printat")
End Using
End If
And also a picture with exported file:
the red circled line is the way that I need for export
the red circle string from code is my input which is mandatory for each line followed by DGV lines export.
Actual TXT export
Actual Code for input my mandatory text before DGV export
Thanks!

Provide some debug detail like what is Rows.Count etc.
If it is not going inside loop and even there are rows, better you try with accessing object in DataSource.
Something like ForEach loop on ((DataTable)DataGridView1.DataSource).Rows

Related

Doubles will not output in DataGridView

I have a DataGridView that I want to fill with values that are Doubles. The DataGridView filled fine when the values were strings, but now it outputs System.Double[] in the first column and nothing in any other column. I know the conversion is working because I can print the double values to the console. How do I format all columns programmatically? (I don't want to use the designer)
My code:
Dim cols() as String = {"col1", "col2", "col3"} ' this goes on for 33 cols
Dim currentRow As String()
Dim row() As Double
Dim c As Integer
DataGridView1.Rows.Clear()
DataGridView1.ReadOnly = True
DataGridView1.DefaultCellStyle.Format = "G"
DataGridView1.ColumnCount = 33
For c = 0 To (cols.Length - 1)
DataGridView1.Columns(c).Name = cols(c)
Next
While Not at EndOfFile ' This line and the next are semi-pseudocode, but it's the same idea
read/parse line into currentRow
Dim x As Integer
For x = 0 To (currentRow.Length - 1)
ReDim Preserve row(x)
Double.TryParse(currentRow(x), row(x))
Next
With Me.DataGridView1.Rows
.Add(row)
End With
Screenshot of the output:
You can first add the row to the grid, then loop through your array to add the information to each cell.
Dim i as integer = DataGridView1.Rows.Add
For x As Integer = 0 to row.Count - 1
DataGridView1.Rows(i).Cells(x).Value = row(x)
Next

Throw ID and its information into listview

I got multiline textbox and ListView
textbox contains :
[1000]
name=John
number0=78569987
[1001]
name=Sara
number0=89768980
number1=77897545
TextBox2.Text = TextBox2.Text.Replace("[", "this what i want")
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
Dim FilterText = "this what i want"
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
TextBox2.Lines = lines.ToArray
TextBox2.Text = TextBox2.Text.Replace("this what i want", "")
TextBox2.Text = TextBox2.Text.Replace("]", "")
ListBox1.Items.AddRange(TextBox2.Lines)
For Each x As String In ListBox1.Items
Dim II As New ListViewItem
II.Text = x
ListView1.Items.Add(II)
Next
I cant use the same way to insert numbers and names because some ids contain number0 number 1 and some contain only number 0 ,, so how can I insert their numbers ?
Thanks in advance.
Check the below code with comments. You might have to modify slightly to fit the data.
Check this question and it's linked questions for similar thing.
Edit: Note that this only copies from rows in richtextbox to different columns in listview, so it will work for the examples you provided. I hope you can refine this logic to account for specific columns as per the data coming in the richtextbox.
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
'Add 1st row to the listview
ListView1.Items.Add(New ListViewItem())
'Use Counter to determine row#
Dim j As Integer = 0
'Loop through the items
For i As Integer = 0 To lines.Count - 1
'Check if it's 1st item i.e. ID and add as text (i.e. at Index 0)
If lines(i).StartsWith("[") Then
ListView1.Items(j).Text = lines(i).Substring(1, lines(i).Length - 2)
'Check if contains other columns with attributes
ElseIf lines(i).Contains("=") Then
ListView1.Items(j).SubItems.Add(lines(i).Substring(lines(i).IndexOf("=") + 1))
'Check if it's an empty record, and add new row to listview
Else
j = j + 1
ListView1.Items.Add(New ListViewItem())
End If
Next

Showing the difference between two RichTextBox controls

I'm trying to compare both richtextbox text and show the difference into the 3rd richtextbox. After i do some changes to the code that i get from this forum, it still have some problems, which is there are words that are no different showing out at my 3rd richtextbox.... the right hand side of the rich text box is from a text file that have been checked in regex function before displayed in the box.
this is the source code that use for compare:
Dim txt1(DispBox.Text.Split(" ").Length) As String
Dim txt2(DispBox2.Text.Split(" ").Length) As String
txt1 = DispBox.Text.Split(" ")
txt2 = DispBox2.Text.Split(" ")
Dim diff1 As String = "" 'Differences between 1 and 2
Dim diff2 As String = "" 'Differences between 2 and 1
Dim diffPosition As Integer ' Set where begin to find and select in RichTextBox
diffPosition = 1 ' Initialize
For Each diff As String In txt1
If Array.IndexOf(txt2, diff.ToString) = -1 Then
diff1 += diff.ToString & " "
With DispBox
.Find(diff, diffPosition, RichTextBoxFinds.None) ' Find and select diff in RichTextBox1 starting from position diffPosition in RichtextBox1
.SelectionFont = New Font(.Font, FontStyle.Bold) ' Set diff in Bold
.SelectionColor = Color.Blue ' Set diff in blue instead of black
.SelectionBackColor = Color.Yellow ' highlight in yellow
End With
End If
diffPosition = diffPosition + Len(diff) ' re-Initialize diffPostion to avoid to find and select the same text present more than once
Next
DispBox3.Visible = True
DispBox3.Text = diff1
this is my upload button code to check the regex function
Dim result As DialogResult = OpenFileDialog1.ShowDialog()
' Test result.
If result = Windows.Forms.DialogResult.OK Then
' Get the file name.
Dim path As String = OpenFileDialog1.FileName
Try
' Read in text.
Dim text As String = File.ReadAllText(path)
Dim postupload As String = Regex.Replace(text, "!", "")
DispBox2.Text = postupload
' For debugging.
Me.Text = text.Length.ToString
Catch ex As Exception
' Report an error.
Me.Text = "Error"
End Try
End If
because inside the text file there will be "!" between the line, I would like to replace the "!" with "breakline/enter".
My problem is :
why the "Building & hostname" words count as wrong words.
why the new word that display in 3rd richtextbox is not in new line if the words is found in the middle of the line.
the other wrong words are not color, bold n highlight.....
Your code is splitting all the words based on a space, but it's ignoring the line breaks, so it makes "running-confing building" look like one word.
Try it this way:
Dim txt1 As String() = String.Join(" ", DispBox.Lines).Split(" ")
Dim txt2 As String() = String.Join(" ", DispBox2.Lines).Split(" ")

Check if first 3 items in listview1 matches one of listview2's items

I'm working on a project where the program gets items from a table and puts it in a listview. Now I want to check if the top 3 items matches the items in another listview i have set up and return a message whether or not listview1 contains any items from listview2. I can do this for the whole listview1 but I want to check the top 3 only.
For Each li As ListViewItem In ListView2.Items
Dim liToFind As ListViewItem = ListView1.FindItemWithText(li.Text)
If Not IsNothing(liToFind) Then
Using New Centered_MessageBox(Me)
MessageBox.Show(li.Text & " has released a new episode!", "New release", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Using
End If
Next
This is the code for what I have so far, im checking the text of the items in listview2 to see if it matches any of the items in listview1, can't figure out how to do it with the top 3 only though.
Help would be greatly apriciated!
Here is an example - obviously you can be cleverer here .
Dim checkrows As Integer = 3
Dim numFound As Integer
For row As Integer = 0 To Math.Min(checkrows - 1, ListView1.Items.Count - 1)
Dim text As String = ListView1.Items(row).Text
Dim found As Boolean
For Each item2 As ListViewItem In ListView2.Items
If text.Contains(item2.Text) Then
found = True
Exit For
End If
Next
If found Then numFound += 1
Next
If numFound > 0 Then MessageBox.Show("At least one of the first " & checkrows.ToString & " rows in ListView1 matches a row in ListView2")
If numFound = checkrows Then MessageBox.Show("The first " & checkrows.ToString & " rows in ListView1 match a row in ListView2")
This worked for me, thanks AltF4 but yours didn't really work out for me. Ty for putting your time into this anyway <3
Dim checkrows As Integer = 3
Dim numFound As Integer
For row As Integer = 0 To Math.Min(checkrows - 1, ListView1.Items.Count - 1)
Dim text As String = ListView1.Items(row).Text
Dim found As Boolean
For Each item2 As ListViewItem In ListView2.Items
If text.Contains(item2.Text) Then
found = True
Exit For
End If
Next
If found Then numFound += 1
Next
If numFound > 0 Then MessageBox.Show("At least one of the first " & checkrows.ToString & " rows in ListView1 matches a row in ListView2")
If numFound = checkrows Then MessageBox.Show("The first " & checkrows.ToString & " rows in ListView1 match a row in ListView2")

What is causing 'Index was outside the bounds of the array' error?

What is causing 'Index was outside the bounds of the array' error? It can't be my file, defianetly not. Below is my code:
Sub pupiltest()
Dim exitt As String = Console.ReadLine
Do
If IsNumeric(exitt) Then
Exit Do
Else
'error message
End If
Loop
Select Case exitt
Case 1
Case 2
Case 3
End Select
Do
If exitt = 1 Then
pupilmenu()
ElseIf exitt = 3 Then
Exit Do
End If
Loop
Dim score As Integer
Dim word As String
Dim totalscore As Integer = 0
'If DatePart(DateInterval.Weekday, Today) = 5 Then
'Else
' Console.WriteLine("You are only allowed to take the test on Friday unless you missed it")
' pupiltest()
'End If
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Dim stdntfname As String = founditem(3)
Dim stdntsname As String = founditem(4)
Dim stdntyear As String = founditem(5)
Console.Clear()
If founditem IsNot Nothing Then
Do
If stdntyear = founditem(5) And daytoday = founditem(6) Then
Exit Do
ElseIf daytoday <> founditem(6) Then
Console.WriteLine("Sorry you are not allowed to do this test today. Test available on " & item(6).Substring(0, 3) & "/" & item(6).Substring(3, 6) & "/" & item(6).Substring(6, 9))
Threading.Thread.Sleep(2500)
pupiltest()
ElseIf stdntyear <> founditem(5) Then
Console.WriteLine("Year not found, please contact the system analysts")
Threading.Thread.Sleep(2500)
pupiltest()
End If
Loop
End If
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\testtests.csv")
Dim item() As String = line.Split(","c)
Dim mine As String = String.Join(",", item(2), item(3), item(4), item(5), item(6))
For i As Integer = 1 To 10
Console.WriteLine(i.ToString & "." & item(1))
Console.Write("Please enter the word: ")
word = Console.ReadLine
If word = Nothing Or word <> item(0) Then
score += 0
ElseIf word = item(0) Then
score += 2
ElseIf word = mine Then
score += 1
End If
Next
If score > 15 Then
Console.WriteLine("Well done! Your score is" & score & "/20")
ElseIf score > 10 Then
Console.WriteLine("Your score is" & score & "/20")
ElseIf score Then
End If
Next
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdntscores", True)
sw.Write(stdntfname, stdntsname, stdntyear, score, daytoday, item(7))
Try
Catch ex As Exception
MsgBox("Error accessing designated file")
End Try
End Using
End
End Sub
All help is highly appreciated,
You are constantly replacing the foundItem array when you do founditem = item:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Also, you are using (=) the assignment operation instead of (==) relational operator, to compare. Refer to this article for help in understanding the difference between the two.
Instead of this: If stdntyear = founditem(5) And daytoday = founditem(6) Then
Use this: If (stdntyear == founditem(5)) And (daytoday == founditem(6)) Then
Now back to your main error. You continue to assign the itemarray to founditem every time you iterate (Which overwrites previous content). At the end of the Iteration you will be left with the last entry in your CSV only... So in other words, founditem will only have 1 element inside of it. If you try to pick out ANYTHING but index 0, it will throw the exception index was outside the bounds of the array
So when you try to do the following later, it throws the exception.
Dim stdntfname As String = founditem(3) 'index 3 does not exist!
To fix it do the following change:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
'NOTE: Make sure you know exactly how many columns your csv has or whatever column
' you wish to access.
Dim item() As String = line.Split(","c)
founditem(0) = item(0) 'Assign item index 0 to index 0 of founditem...
founditem(1) = item(1)
founditem(2) = item(2)
founditem(3) = item(3)
founditem(4) = item(4)
founditem(5) = item(5)
founditem(6) = item(6)
Next
For more help on how to work with VB.NET Arrays visit this site: http://www.dotnetperls.com/array-vbnet
In your line Dim item() As String = line.Split(","c) there's no guarantee that the correct number of elements exist. It's possible that one of the lines is missing a comma or is a blank trailing line in the document. You might want to add a If item.Length >= 7 and skipping rows that don't have the right number of rows. Also, remember that unlike VB6, arrays in .Net are 0 based not 1 based so make sure that item(6) is the value that you think it is.