Exclude records from the first and last rows in a loop - vb.net

Below is my export to csv from listview using vb.net
Function ExportListview2CSV(ByVal lstview As ListView) As Boolean
Dim saveFileDialog1 As New SaveFileDialog()
Dim csvFileContents As New System.Text.StringBuilder
Dim CurrLine As String = String.Empty
saveFileDialog1.Filter = "CSV|*.csv"
saveFileDialog1.Title = "Save an CSV File"
csvFileContents.AppendLine("Service Provider Name: |" & cbodestproname.Text)
'csvFileContents.AppendLine(cbodestproname.Text)
csvFileContents.AppendLine("Circel Name: |" & cbodestcirclename.Text)
'csvFileContents.AppendLine(cbodestcirclename.Text)
csvFileContents.AppendLine("Month: |" & dtpDate.Text)
' csvFileContents.AppendLine(dtpDate.Text)
csvFileContents.AppendLine("Type of File: |" & cbotypeoffile.Text)
' csvFileContents.AppendLine(cbotypeoffile.Text)
csvFileContents.AppendLine("")
'Write out the column names as headers for the csv file.
For columnIndex As Int32 = 1 To lstview.Columns.Count - 2
CurrLine &= (String.Format("{0}|", lstview.Columns(columnIndex).Text))
Next
'Remove trailing comma
csvFileContents.AppendLine(CurrLine.Substring(0, CurrLine.Length - 1))
CurrLine = String.Empty
'Write out the data.
For Each item As ListViewItem In lstview.Items
For Each subItem As ListViewItem.ListViewSubItem In item.SubItems
CurrLine &= (String.Format("{0}|", subItem.Text))
Next
'Remove trailing comma
csvFileContents.AppendLine(CurrLine.Substring(0, CurrLine.Length - 1))
CurrLine = String.Empty
Next
'Create the file.
If saveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
If saveFileDialog1.FileName <> "" Then
Dim Sys As New System.IO.StreamWriter(saveFileDialog1.FileName)
Sys.WriteLine(csvFileContents.ToString)
Sys.Flush()
Sys.Dispose()
MsgBox("Data's are Saved Succesfully to " & saveFileDialog1.FileName, MsgBoxStyle.Information)
End If
End If
End Function
i want to exclude the records from the 1st and last rows
where should i make chages in above code
plz help me
thanx in advance.

You might use
For i as Integer = 1 to lstview.Items.Count - 2
...
Next
that will start from the second item and stop before the last item

yeah, you should use an index other than for each to iterate the items in listview

Related

Comparing text in two Richtextboxes and get the differences

I'm want to compare the text between two richtextboxes and get the differences in the third one. Without highlight the text.
So far, the best option is this solution
The first solution works, but it doesn't remove the text present in richtextbox2 from the richtextbox1.
Endeed, the user asked
if they are the same do nothing.
My case is complete the opposite and still i cannot find a solution.
Thanks
First, you need to add a combobox to your form named (combobox1)
then add these items in it:
RichTextbox1 - RichTextbox2
RichTextbox2 - RichTextbox1
second, add a button named (button1), under this button click event
insert this code:
RichTextBox3.Clear()
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox1 - RichTextbox2" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff1 As String = ""
For Each diff As String In txt1
If Array.IndexOf(txt2, diff.ToString) = -1 Then
diff1 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff1.ToString
End If
If RichTextBox1.Text <> "" And RichTextBox2.Text <> "" And RichTextBox1.Text <> RichTextBox2.Text And ComboBox1.SelectedItem = "RichTextbox2 - RichTextbox1" Then
Dim txt1(RichTextBox1.Text.Split(" ").Length) As String
Dim txt2(RichTextBox2.Text.Split(" ").Length) As String
txt1 = RichTextBox1.Text.Split(" ")
txt2 = RichTextBox2.Text.Split(" ")
Dim diff2 As String = ""
For Each diff As String In txt2
If Array.IndexOf(txt1, diff.ToString) = -1 Then
diff2 += diff.ToString & " "
End If
Next
RichTextBox3.Text = diff2.ToString
End If
now, you have 2 options:
if you choose (RichTextbox1 - RichTextbox2) from the combobox then click the button, richtextbox3 will display the text which is found in richtextbox1 and not found in richtextbox2, while if you choose (RichTextbox2 - RichTextbox1), the opposite will happen
finally, if the 2 richtextboxes is the same, nothing will occur
Also you could use String.Join *
Under Button1 click event replace this code with the previous one:
Dim intsA = RichTextBox1.Text.Split(" ")
Dim intsB = RichTextBox2.Text.Split(" ")
Dim myresult = intsA.Except(intsB).ToArray()
RichTextBox3.Text = String.Join(" ", myresult)
if you found this useful, mark it as answer

Skip the first line of the CSV file (Headers) Visual Basic

Like many on here, I am new to programming and mainly focus on web development. I have written a program cobbled together from help on here that works perfectly. I take a CSV file and inject it into an SQL database. I am getting a "MalformedLineException" line exception on the last line of the CSV file and believe it is because the header line is not being skipped.
Would love some help on working out how to skip the first line from my code below:
Private Sub subProcessFile(ByVal strFileName As String)
'This is the file location for the CSV File
Using TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(strFileName)
'removing the delimiter
TextFileReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
TextFileReader.SetDelimiters(",")
ProgressBar1.Value = 0
Application.DoEvents()
'variables
Dim TextFileTable As DataTable = Nothing
Dim Column As DataColumn
Dim Row As DataRow
Dim UpperBound As Int32
Dim ColumnCount As Int32
Dim CurrentRow As String()
'Loop To read in data from CSV
While Not TextFileReader.EndOfData
Try
CurrentRow = TextFileReader.ReadFields()
If Not CurrentRow Is Nothing Then
''# Check if DataTable has been created
If TextFileTable Is Nothing Then
TextFileTable = New DataTable("TextFileTable")
''# Get number of columns
UpperBound = CurrentRow.GetUpperBound(0)
''# Create new DataTable
For ColumnCount = 0 To UpperBound
Column = New DataColumn()
Column.DataType = System.Type.GetType("System.String")
Column.ColumnName = "Column" & ColumnCount
Column.Caption = "Column" & ColumnCount
Column.ReadOnly = True
Column.Unique = False
TextFileTable.Columns.Add(Column)
ProgressBar1.Value = 25
Application.DoEvents()
Next
clsDeletePipeLineData.main()
End If
Row = TextFileTable.NewRow
'Dim Rownum As Double = Row
'If Rownum >= 1715 Then
' MsgBox(Row)
'End If
For ColumnCount = 0 To UpperBound
Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
Next
TextFileTable.Rows.Add(Row)
clsInsertPipeLineData.main(CurrentRow(0).ToString, CurrentRow(1).ToString, CurrentRow(2).ToString, CurrentRow(3).ToString, CurrentRow(4).ToString, CurrentRow(5).ToString, CurrentRow(6).ToString, CurrentRow(7).ToString, CurrentRow(9).ToString)
ProgressBar1.Value = 50
Application.DoEvents()
End If
Catch ex As _
Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
ProgressBar1.Value = 100
Application.DoEvents()
clsMailConfirmation.main()
TextFileReader.Dispose()
MessageBox.Show("The process has been completed successfully")
End Using
"MalformedLineException" says that Line cannot be parsed using the current Delimiters, to fix it, adjust Delimiters so the line can be parsed correctly, or insert exception-handling code in order to handle the line.
Someone encountered similar question, maybe its reply can help you.

Export to csv in debug mode success but in run-time mode it fails

I am reading records from a SQL Server table into a dataset and then exporting it to a CSV file. When I step through it in debug mode, everything works fine. When I run it, it exports just one cell with crap data. Since it is an ASP.NET application I am not sure if I am doing something wrong regarding postbacks. It seems in run-time, it doesn't wait for the CSV file to be written.
Dim sbldRecordCSV As New StringBuilder
Dim dtHCMTable As DataTable = mdsHCMTable.Tables(0)
Dim intIndex As Integer = 0
'Read the connection-string from web.config
Dim connHCM As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("connHCM").ConnectionString)
'Read the exported CSV file path from web.config
Dim strCSVpath As String = System.Configuration.ConfigurationManager.AppSettings("CSVpath").ToString
Try
For intIndex = 0 To mdsHCMTable.Tables(0).Rows.Count - 1
Dim drHCMTable As DataRow = dtHCMTable.Rows(intIndex)
For Each field As Object In drHCMTable.ItemArray
sbldRecordCSV.Append(field.ToString & "|")
Next
sbldRecordCSV.Replace("|", vbNewLine, sbldRecordCSV.Length - 1, 1)
Next
My.Computer.FileSystem.WriteAllText(strCSVpath.ToString & lstDataTables.SelectedValue.ToString & ".csv", sbldRecordCSV.ToString, False)
After some searching around I realized that I neede to modify the ExportCSV code. The modified routine is as follows:
Protected Sub ExportToCSV(mdsHCMTable As DataSet)
Dim dt As DataTable = mdsHCMTable.Tables(0)
'Read the exported CSV file path from web.config
Dim strCSVpath As String = System.Configuration.ConfigurationManager.AppSettings("CSVpath").ToString
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=" & lstDataTables.SelectedValue.ToString & ".csv")
Response.Charset = ""
Response.ContentType = "application/text"
Dim sb As New StringBuilder()
For k As Integer = 0 To dt.Columns.Count - 1
'add separator
sb.Append(dt.Columns(k).ColumnName + "|"c)
Next
'append new line
sb.Append(vbCr & vbLf)
For i As Integer = 0 To dt.Rows.Count - 1
For k As Integer = 0 To dt.Columns.Count - 1
'add separator
sb.Append(dt.Rows(i)(k).ToString().Replace(",", "|") + "|"c)
Next
'append new line
sb.Append(vbCr & vbLf)
Next
Response.Clear()
Response.BufferOutput = False
Response.Output.Write(sb.ToString())
Response.Flush()
End Sub
This solution worked for me. I hope it can be helpful to others.

Listbox1 add all the items to richtextbox in the same format

I'm trying to get all the ListBox1 items and have them go to the RichTextBox1. I want it in the same format that it's in the ListBox1. I've tried different code and they seem to give extra blank lines in between items. So far I've thought of this but it give extra blank lines.
Dim counter As String
counter = ListBox1.Items.Count - 1
ListBox1.SelectedIndex = 0
If ListBox1.SelectedIndex = 0 Then
Do Until ListBox1.SelectedIndex = counter
ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
RichTextBox1.Text = RichTextBox1.Text & vbNewLine & ListBox1.SelectedItem
Loop
End If
Use LINQ to select all the items and join on Environment.NewLine:
.Net >= 4.0
Me.RichTextBox1.Text = String.Join(Environment.NewLine, (From item As Object In Me.ListBox1.Items Select Me.ListBox1.GetItemText(item).Trim()))
.Net >= 3.5
Me.RichTextBox1.Text = String.Join(Environment.NewLine, (From item As Object In Me.ListBox1.Items Select Me.ListBox1.GetItemText(item).Trim()).ToArray())
you are adding a vbNewLine before you add the ListBox text... you should put that at the end of the line RichTextBox1.Text = RichTextBox1.Text & ListBox1.SelectedItem & vbNewLine and you also shouldn't increment your selected index value until after you add the line...
Alternatively, You can do this..
For i = 0 To ListBox1.Items.Count - 1
RichTextBox1.Text = RichTextBox1.Text & ListBox1.Items(i) & vbCrLf
Next
OR this SO question has a few good examples using LINQ and condensed query code...
passing all the items of listbox in the richtextbox
This is because initially the richtextbox is empty. Hence RichTextBox1.Text = RichTextBox1.Text & vbNewLine & ListBox1.SelectedItem will add a New Line first and the add the second element of list to the richtextbox, this is because you incremented the selected index value by 1 before adding to the richtexbox. So your code can be used in an effective way as follows:
Dim counter As Integer = ListBox1.Items.Count - 1
ListBox1.SelectedIndex = 0
If ListBox1.SelectedIndex = 0 Then
Do Until ListBox1.SelectedIndex = counter
RichTextBox1.Text = RichTextBox1.Text & ListBox1.SelectedItem & vbNewLine
ListBox1.SelectedIndex = ListBox1.SelectedIndex + 1
Loop
End If
try saving the listbox to a file using a streamwriter and writeline(), then opening it into a text box using streamreader and readtoend()
'assuming you have the default names
dim reader As streamreader, writer As streamwriter
writer = new streamwriter("TMP")
for each x as object in listbox1.items
writer.writeline(X)
next
writer.close()
reader=new streamreader("TMP")
textbox1.text=reader.readtoend()
reader.close()

extracting text from comma separated values in visual basic

I have such kind of data in a text file:
12343,M,Helen Beyer,92149999,21,F,10,F,F,T,T,T,F,F
54326,F,Donna Noble,92148888,19,M,99,T,F,T,F,T,F,T
99999,M,Ed Harrison,92147777,28,F,5,F,F,F,F,F,F,T
88886,F,Amy Pond,92146666,31,M,2,T,F,T,T,T,T,T
37378,F,Martha Jones,92144444,30,M,5,T,F,F,F,T,T,T
22444,M,Tom Scully,92145555,42,F,6,T,T,T,T,T,T,T
81184,F,Sarah Jane Smith,92143333,22,F,5,F,F,F,T,T,T,F
97539,M,Angus Harley,92142222,22,M,9,F,T,F,T,T,T,T
24686,F,Rose Tyler,92142222,22,M,5,F,F,F,T,T,T,F
11113,F,Jo Grant,92142222,22,M,5,F,F,F,T,T,T,F
I want to extract the Initial of the first name and complete surname. So the output should look like:
H. Beyer, M
D. Noble, F
E. Harrison, M
The problem is that I should not use String Split function. Instead I have to do it using any other way of string handling.
This is my code:
Public Sub btn_IniSurGen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_IniSurGen.Click
Dim vFileName As String = "C:\temp\members.txt"
Dim vText As String = String.Empty
If Not File.Exists(vFileName) Then
lbl_Output.Text = "The file " & vFileName & " does not exist"
Else
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine() & vbNewLine
lbl_Output.Text += vText.Substring(8, 1)
Loop
rvSR.Close()
End If
End Sub
You can use the TextFieldParserClass. It will parse the file and return the results directly to you as a string array.
Using MyReader As New Microsoft.VisualBasic.FileIO.
TextFieldParser("c:\logs\bigfile")
MyReader.TextFieldType =
Microsoft.VisualBasic.FileIO.FieldType.Delimited
MyReader.Delimiters = New String() {","}
Dim currentRow As String()
'Loop through all of the fields in the file.
'If any lines are corrupt, report an error and continue parsing.
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
' Include code here to handle the row.
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
" is invalid. Skipping")
End Try
End While
End Using
For your wanted result, you may changed
lbl_Output.Text += vText.Substring(8, 1)
to
'declare this first
Dim sInit as String
Dim sName as String
sInit = vText.Substring(6, 1)
sName = ""
For x as Integer = 8 to vText.Length - 1
if vText.Substring(x) = "," Then Exit For
sName &= vText.Substring(x)
Next
lbl_Output.Text += sName & ", " & sInit
But better you have more than one lbl_Output ...
Something like this should work:
Dim lines As New List(Of String)
For Each s As String In File.ReadAllLines("textfile3.txt")
Dim temp As String = ""
s = s.Substring(s.IndexOf(","c) + 1)
temp = ", " + s.First
s = s.Substring(s.IndexOf(","c) + 1)
temp = s.First + ". " + s.Substring(s.IndexOf(" "c), s.IndexOf(","c) - s.IndexOf(" "c)) + temp
lines.Add(temp)
Next
The list Lines will contain the strings you need.