I am wanting to take a txt file that I have that is comma separated. For example:
706202212011417.G001,1024,20221201,172300,3600,35479,....
I am trying to figure out how to make an ArrayList and assign each individual comma separated value as an it's own item put it anywhere in the list.
For example, I want to assign the first comma-separated value to an A1 variable, and then use this variable in a MessageBox: "A1 is ******.***"
I have been able to separate everything out, but I cannot seem to set the array to assign each item to its own variable.
Using MyReader As New Microsoft.VisualBasic.
FileIO.TextFieldParser(
"C:\TestFolder\test.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
Look more closely at the currentRow variable. This provides an index variable you can use to target individual values in the row: currentRow(0), currentRow(1), etc.
Related
I've been trying to create a leaderboard a little maze game I'm creating and im using a CSV File to store my data. I have two fields per row, something akin to
James, 20
Luke, 34
Which is "playername" and "score".
Whenever i run the code [below], my listbox displays;
James
20
Luke
34
I'm attempting to display it as something such as
James 20
Luke 34
I've tried to store the first field as a string and grab the next field and concatenate the two together to display it on one line, however i was unable to grab the next field as it would result in a recoding of the reading function.
FileIO.TextFieldParser(
"C:\Users\zamks1622\Desktop\Computing\SAT\Leaderboard.csv")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
ListLeaderboard.Items.Add(currentField)
Next
Catch ex As Microsoft.VisualBasic.
FileIO.MalformedLineException
MsgBox("Line " & ex.Message &
"is not valid and will be skipped.")
End Try
End While
End Using
I think this may help
Try
currentRow = MyReader.ReadFields()
ListLeaderboard.Items.Add(Join(currentRow , " "))
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
Unable to get the excepted result due to the following error
Conversion from string " to type 'integer' is not valid'
I have been able to load values from the products table, add selected ones to Selected Products and then search all the selected products against the Customers table to find out how many customers ordered these products.
Try
Dim ListOfDiag As StringBuilder = New StringBuilder()
For Each row As DataGridViewRow In SelectedDiagDGV.Rows
ListOfDiag.Append(row.Cells(0).Value.ToString & "", "" & Environment.NewLine)
Next
Dim query As String = String.Empty
Dim SegmentConnectionString As String = "Data Source=Test-PC;Initial Catalog=TestDB;Integrated Security=True"
query = "SELECT Customers, ProductName from Customers WHERE ProductName in (" & ListOfDiag.ToString & ")"
Dim dTable As DataTable = New DataTable()
Dim dAdapter As SqlDataAdapter
dAdapter = New SqlDataAdapter(query, SegmentConnectionString)
dAdapter.Fill(dTable)
DataGridView1.DataSource = dTable
'Next
Catch ex As System. Exception
MsgBox(ex.Message.ToString)
End Try
Unable to perform a for loop search. Some of the values contain special characters example: Soft ’Drink’; Computer (Desk).
Error: Conversion from string " to type 'Integer' is not valid.
ListOfDiag.Append(row.Cells(0).Value.ToString & "", "" & Environment.NewLine)
There is no overload of StringBuilder.Append that takes (String, String) as arguments. the first string is row.Cells(0).Value.ToString & "" and then there is a comma between parameters and the second string is "" & Environment.NewLine Remember that "" is an empty string, not escape characters. Not sure what your intention was but this will not work.
You had the right approach; to build a string for the In clause. I used a List(Of String) to get the data from the rows then after the loop I used a .Join with a comma separator to get the value for the In clause.
I passed the connection string directly to the constructor of the Connection and passed the Select statement and the connection to the constructor of the Command. For the Select statement I used and Interpolated String (the string preceded by the $) You could also use String.Format in older version of Visual Studio.
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
I think the only special character that could mess things up would be the presence of a comma in a Product Name.
Private Sub OPCode()
Dim dTable As New DataTable
Dim ListOfDiag As New List(Of String)
For Each row As DataGridViewRow In SelectedDiagDGV.Rows
ListOfDiag.Add(row.Cells(0).Value.ToString)
Next
Dim InData = String.Join(",", ListOfDiag)
Using cn As New SqlConnection("Data Source=Test-PC;Initial Catalog=TestDB;Integrated Security=True")
Using cmd As New SqlCommand($"SELECT Customers, ProductName from Customers WHERE ProductName in ({InData})", cn)
cn.Open()
dTable.Load(cmd.ExecuteReader)
End Using
End Using
DataGridView1.DataSource = dTable
End Sub
(I don't need alternatives to OleDbDataAdapter.)
The code below finds and reads the file OK but the DGV has four columns (as expected) but all the data rows just have text in the first column.
Dim sDir As String = "c:\temp\"
Dim sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sDir & ";Extended Properties='text;HDR=Yes;FMT=TabDelimited';"
Dim dt As New DataTable()
Using adapt As New OleDbDataAdapter(String.Format("SELECT TOP 100 * FROM robo.txt"), sConn)
adapt.Fill(dt)
End Using
DataGridView1.DataSource = dt
I would think the Extended Properties would be the only requirement. I've tried add a Schema.ini to no avail - I don't think it is even being read as the column headers never match the schema.
The header row in the most successful pass used commas as separator - this resulted in four columns with the proper names but the tab separated data all in Col1. If I use tabs in the header row I get some system assign columns (3) which sort of corresponds to a data row with two commas.
What am I doing wrong?
Here are the first few rows with the tab character being replaced by <tab> . I since noticed that I have an extra column in the data. The fix to the header row below did not fix the problem - all data is dumped into the first field.
Use a tab separator in the header, instead of commas, results in all header text and the data being dumped into the first field.
col1,state,col3,size,path
<tab> same<tab><tab> 102912<tab>\\APCD04T\Data\Thumbs.db
<tab> same<tab><tab> 22016<tab>\\APCD04T\Data\APCD Topical Info\APCD_Boards&Committees_List.doc
<tab> same<tab><tab> 4.3 m<tab>\\APCD04T\Data\APCD Topical Info\LOSSAN-LAtoSLORailCorridorStrategicPlan.pdf
Learned several things while trying to load a RoboCopy log into a DataTable using OLEDB.
log file needs to have a .txt or .csv (or ?) extension, .log fails.
Schema.ini seems to be needed for tab delimited robocopy log, good for column definition anyway.
Datagridview takes a long time to display 30MB of data so I used
filters
I borrowed code from the net to create a Schema.ini as noted below
(SO bug: code will not paste from Visual Studio anymore. Code tool flips to other web page for Java.)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Cursor = Cursors.WaitCursor
'http://ss64.com/nt/robocopy.html can suppress header and summary
Dim sFile As String = "c:\temp\robo.txt" ' seems to need a .txt or .csv, .log didn't work
CreateRoboLogSchema(sFile) ' recreates each pass, no needed once things work
Dim sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & IO.Path.GetDirectoryName(sFile) & ";Extended Properties='text';"
' use Schema.ini for: HDR=Yes;FMT=TabDelimited' and column definitions
Dim dt As New DataTable()
Dim SQL As String = "SELECT * FROM " & IO.Path.GetFileName(sFile)
'SQL &= " WHERE State <> 'Same'"
Using adapt As New OleDbDataAdapter(SQL, sConn)
adapt.Fill(dt)
End Using
Debug.Print("|" & dt.Rows(0)(1) & "|") ' show import trimmed leading spaces (trims trailing too)
' DGV slow to load large files, use filter to display target rows
Dim dv As New DataView(dt)
dv.RowFilter = "State <> 'Same'" ' not case sensitive
DataGridView1.DataSource = dv
DataGridView1.Columns(0).Visible = False
DataGridView1.AutoResizeColumns()
Catch ex As Exception
MsgBox(ex.Message)
Finally
'Cursor=Cursors.Default
End Try
End Sub
Private Function CreateRoboLogSchema(ByVal strFileName As String) As Boolean
' edit http://www.vb-tips.com/CSVDataSet.aspx
Dim ascii As System.Text.Encoding = System.Text.Encoding.ASCII
Dim swSchema As System.IO.StreamWriter = Nothing
Dim blnReturn As Boolean
Dim strSchemaPath As String = System.IO.Path.GetFileName(strFileName)
Try
strSchemaPath = IO.Path.GetDirectoryName(strFileName) & "\Schema.ini"
swSchema = My.Computer.FileSystem.OpenTextFileWriter(strSchemaPath, False, ascii)
Dim strFile As String = System.IO.Path.GetFileName(strFileName)
swSchema.WriteLine("[" & IO.Path.GetFileName(strFileName) & "]")
swSchema.WriteLine("ColNameHeader=False")
swSchema.WriteLine("Format=TabDelimited")
swSchema.WriteLine("Col1=Value1 Text") ' file specific
swSchema.WriteLine("Col2=State Text")
swSchema.WriteLine("Col3=DirChanges Text")
swSchema.WriteLine("Col4=Size Text")
swSchema.WriteLine("Col5=Filepath Text")
'Continue for all fields
blnReturn = True
Catch ex As Exception
blnReturn = False
Finally
If swSchema IsNot Nothing Then
swSchema.Close()
End If
End Try
Return blnReturn
End Function
I want to make a chart with several series on it. Every series belongs to a particular person.
First I read out the number of different persons in my table in Access:
connection.Open()
command.CommandText = "SELECT kontoverlauf_kunden_id FROM kontoverlauf GROUP BY kontoverlauf_kunden_id"
Dim kunden_id_array As New ArrayList()
reader = command.ExecuteReader()
Do While reader.Read()
kunden_id_array.Add(reader("kontoverlauf_kunden_id").ToString())
Loop
reader.Close()
connection.Close()
Now I have the different persons (the ID of them).
Second I add the series i need to the chart:
For counter As Integer = 0 To kunden_id_array.Count - 1
chartKontoverlauf.Series.Add(New Series("Konto [" & kunden_id_array.Item(counter) & "]"))
chartKontoverlauf.Series(counter).ChartType = SeriesChartType.Line
chartKontoverlauf.Series(counter).Color = Color.Red
chartKontoverlauf.Series(counter).BorderWidth = 3
Next
Now I just need to fill in the points I need, but that's kinda tricky.
I've made a function that will call every time and it reads out the values (money and time) for the particular person. Here's the function first:
Function DatenAuslesen(ByVal kunden_id As Integer) As ListViewItem
Dim lstViewItem As New ListViewItem
Try
connection.Open()
command.CommandText = "SELECT * FROM kontoverlauf WHERE kontoverlauf_kunden_id = " & kunden_id
reader = command.ExecuteReader()
Do While reader.Read()
lstViewItem.SubItems.Add(reader("kontoverlauf_wert").ToString())
lstViewItem.SubItems.Add(reader("kontoverlauf_datum").ToString())
Loop
reader.Close()
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
connection.Close()
Return lstViewItem
End Function
To add the points now, I wrote this little thing:
For counter As Integer = 0 To kunden_id_array.Count - 1
For counter_2 As Integer = 0 To DatenAuslesen(kunden_id_array.Item(counter)).ListView.Items.Count - 1
chartKontoverlauf.Series(counter).Points.AddXY(DatenAuslesen(kunden_id_array.Item(counter)).ListView.Items(counter_2).SubItems(0).Text, DatenAuslesen(kunden_id_array.Item(counter)).ListView.Items(counter_2).SubItems(1).Text)
Next
Next
The problem with the thing is that it just gives me one of the values I need back, and not all. I can't access alle values properly. I'm still not sure if it's even the best variable to do this. I would need an array of ListViewItems to add all of them but I didn't found how to do this.
Maybe anyone has an idea?
Thank you!
I'm trying to create a program which has a datagridview, when the user clicks on a cell in the view, it then looks in a SQL database, grabs information from other fields in the same record, and automatically fills corresponding text boxes (done by manipulating the name of the field) in the form.
For some reason however, I'm getting an error message saying:
"InvalidOperationException was unhandled"
"No Data exists for the row / column"
Here is the code relevant to this part of the program:
Private Sub DataGridView1_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvResults.CellMouseClick
' Set values in the text boxes to both corresponding to the film.
Dim strFields() As String = {"ID", "fName", "fGenre", "fSynopsis", "fAgeRating", "fActorsActresses", "fWebRating", "fNoReservations", "fWeeksRunning"}
Dim Con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=ApplicationData.accdb;Persist Security Info=False;")
Con.Open() 'Open the connection
Dim Cmd As New OleDbCommand(StringBuilderCommand("*", "Films", dgvResults.CurrentCell.Value, "fName"), Con) 'Create a string by calling the StringBuilderCommand to combine the parameters together with quotes.
Cmd.CommandType = CommandType.Text
Dim Rdr As OleDbDataReader = Cmd.ExecuteReader()
Dim intCount As Integer = 4 ' Create a loop variable.
Do While Rdr.Read() Or intCount < 6 ' While this statement is 'TRUE', e.g. there is a valid record.
strResult = "txt" & strFields(intCount).Replace("f", "") 'Remove any instances of 'f', e.g. the prefix of the string.
txtActorsActresses.Text = StringBuilderCommand("*", "Films", dgvResults.CurrentCell.Value, "fName")
Me.Controls(strResult).Text = Rdr.Item(strFields(intCount)) ' Suspect the error lies here.
'Set the text-box to the correct value from the database.
'This will allow me to go through several text boxes, and grab their corresponding values from the database.
intCount = intCount + 1
'Current error is because it cannot find any data beyond the first field taken.
'I have no idea why this is. But if I change the starting intCount value, it will successfully take a different value.
Loop
Rdr.Close() 'Cleaning up.
Cmd.Dispose()
Con.Close()
WebBrowser1.Navigate(dgvResults.CurrentCell.Value.Replace(" ", ".") & ".movie.poster.new.jpg.to") 'Grab the movie poster off the internet corresponding to the films name.
End Sub
Private Function StringBuilderCommand(Field, Table, CurrentCellValue, SearchParameter)
'Creates a suitable SQL string.
Dim MyStringBuilder As New StringBuilder("SELECT ")
MyStringBuilder.Append("*") ' Append the parameter 'Field'.
MyStringBuilder.Append(" FROM ") ' Append the SQL command 'FROM'.
MyStringBuilder.Append(Table) ' Append the parameter 'Table'.
MyStringBuilder.Append(" WHERE ") ' Append the SQL command 'WHERE'.
MyStringBuilder.Append(SearchParameter) ' Append the parameter 'SearchParameter'.
MyStringBuilder.Append("=""")
MyStringBuilder.Append(CurrentCellValue) ' Append the parameter 'CurrentCellValue', representing the cell selected.
MyStringBuilder.Append("""") 'Append a quotation mark.
Return MyStringBuilder.ToString() ' Return it to the main program.
End Function
Database table being connected to:
A view of the error as it looks in Visual Studio 2012 Express:
The value of 'dgvResults.CurrentCell.Value' is the name of a film taken from the database (e.g. "12 Years a Slave").
What am I doing wrong?
Thanks,
C.
The problem is caused by the value of strFields(intCount) you are passing to the reader. It is not a valid column index.
You probably want to loop on the fields before looping again on DataReader(), like:
Do While Rdr.Read()
For intCount as Integer = 4 to 6
strResult = "txt" & strFields(intCount).Replace("f", "")
txtActorsActresses.Text = StringBuilderCommand("*", "Films", dgvResults.CurrentCell.Value, "fName")
Me.Controls(strResult).Text = Rdr.Item(strFields(intCount))
Next
Loop
I removed the Dim intCount As Integer = 4 because it is no longer needed because of the for next loop.