Listing table items as String for VB - mysql

I've been trying to output my results from a table as a String for awhile now. Whenever I use a query in my table and call the Field Table Adapter, it will always show a foreign key constraint exception. I have deleted all my primary and foreign keys to test but it still shows the same exception. I have tried using this code to output to a textbox :
Public Sub listfields()
Dim ds As New DataSet
Dim dt As DataTable = ds.Tables.Item("")
Dim fieldname As String = Field_nameComboBox.SelectedItem
dt = FieldvalueTableAdapter.GetData
Dim i As Integer = 0
While i < dt.Rows.Count
txtbx_field_list.Text = dt.Rows(i).Item("field_name")
txtbx_field_list2.Text = dt.Rows(i).Item("field_value")
txtbx_field_list3.Text = dt.Rows(i).Item("sort_priority")
i += 1
End While
End Sub
However, this shows the last item in the array only. Is there a way to either use a query to output data I want as a string or a method of placing the results into a string?
Thank you.

if you want to show all you records in one textBox with delimiter |
use :
Dim i As Integer = 0
While i < dt.Rows.Count - 1
txtbx_field_list.Text += " | " & dt.Rows(i).Item("field_name") & " | " & Environment.NewLine
txtbx_field_list2.Text += " | " & dt.Rows(i).Item("field_value") & " | " & Environment.NewLine
txtbx_field_list3.Text += " | " & dt.Rows(i).Item("sort_priority") & " | " & Environment.NewLine
i += 1
End While
I still don;t uderstand what you want:
+---------------------+------------------------------+---------------------+
|Name 1 | Name2 | Name 3 | Val 1 Val2 Val3|sort1 sort2 sort3|
or you want
Name1 | val1 | sort1 |
Name2 | val2 | sort2 | etc..

You are overriding each of the text Box variables on each loop iteration.
Change the '=' to '+=' to get all items,
add delimiters if necessary.

Related

Select and display all rows belonging to a specific ID

I have
Table student, student_subject and subject_bsit
"student"
-----------------------
|studentID | FullName |
-----------------------
|1234 | John |
|1235 | Michael |
|1236 | Bryce |
"subject_bsit"
-----------------------------------
|subject_id| subject_name |grade |
-----------------------------------
| 1 | Programming | 3 |
| 2 | Networking | 2.5 |
| 3 | Algorithm | 1.75|
| 4 | Physical Educ | 2 |
This is the Junction table to connect the
two now.
"student_subject"
----------------------------
| student_id | subject_id |
----------------------------
| 1235 | 1 |
| 1235 | 2 |
| 1235 | 3 |
| 1234 | 1 |
As you can see the table ID 1235 is michael He has three three subjects, subject_id 1,2 and 3. What I want to do is to display all the subject name and grades of michael in textboxes, not in a datagrid view.
As of now I still have failed to output it to textboxes. This is my sample query
sql = "SELECT subject_name " & _
" FROM student_subject " & _
" INNER JOIN subject_bsit ON subject_bsit.subject_id = student_subject.sub_id" & _
" where student_subject.student_id='" & Txtbox.Text & "'"
The Txtbox.text in the last query is where the user will input the ID number.
This is my code on displaying the data to the textbox. I don't have any idea or approach on how can i loop on the textbox and display it on each textbox.
cmd = New MySqlCommand(sql, myconn)
dr = cmd.ExecuteReader
While dr.Read
TextBox1.Text = dr.Item("subject_name").ToString
TextBox2.Text = dr.Item("subject_name").ToString
End While
This is the sample User Interface of what i am trying to achieve. Thank you so much.
When you read a query's resultset, you use a loop as you know.
While dr.Read
' run this for every row in your resultset
...
End While
The While loop keeps going until you have read all the rows.
You don't have to use a loop. If you wish you can read the rows one at a time, like this
If dr.Read
' just the first row
End If
If dr.Read
' just the second row
End If
If dr.Read
' just the third row
End If
...
From your question I guess you have Textbox1, Textbox2, ... Textbox5 on your form. I also guess you have Grade1, Grade2 ....
To handle both of the subject name and grade, change the first line of your query to
sql = "SELECT subject_name, grade " & _
You can populate those items like this:
If dr.Read
TextBox1.Text = dr.Item("subject_name").ToString
Grade1.Text = dr.Item("grade").ToString
End If
If dr.Read
TextBox2.Text = dr.Item("subject_name").ToString
Grade2.Text = dr.Item("grade").ToString
End If
If dr.Read
TextBox3.Text = dr.Item("subject_name").ToString
Grade3.Text = dr.Item("grade").ToString
End If
' more of these sets of four lines to fill your whole form.
This solves your problem. But you probably notice it is absurdly repetitive. What you really need is an array (actually two arrays) of textboxes. You create, and then fill in, these texboxes in your program. I have not debugged this: that is for you do to.
Dim Subjects As Textbox()
Dim Grades As Textbox()
...
Dim rownumber, Y
rownumber = 0
Y = 200
Dim Subject
Dim Grade
While dr.Read
Subject = New Textbox
Subject.Text = dr.Item("subject_name").ToString
Subject.Width = 200
Subject.Height = 40
Subject.X = 175
Subject.Y = Y
Subjects(rownumber) = Subject
Form.Controls.Add(Subject)
Grade = New Textbox
Grade.Text = dr.Item("grade").ToString
Grade.Width = 50
Grade.Height = 40
Grade.X = 400
Grade.Y = Y
Grades(rownumber) = Grade
Form.Controls.Add(Grade)
rownumber = rownumber + 1
Y = Y + 50
End While
When this runs you will have two columns of controls, one for each subject. But this code is complex, and you have to do all the layout of your form with Something.Y = value and then Y = Y + 50 arithmetic.
That's why grid controls exist. They take care of that kind of thing.
If you are looking to create Textboxes dynamically then you should refer to the #OJones answer
You can simply loop over Me.Controls.OfType(Of TextBox)()
cmd = New MySqlCommand(sql, myconn)
dr = cmd.ExecuteReader
While dr.Read
For Each txt As TextBox In Me.Controls.OfType(Of TextBox)()
txt.Text = dr.Item("subject_name").ToString
Next
End While
Or you can do a similar approach if you need to fill the first subjects name inside the textboxes (if returned subjects are more than textboxes additional subjects will be ignored):
While dr.Read = True
Dim txt As New TextBox = DirectCast(Me.Controls.Find(string.Format("Textbox{0}", cnt ),false).FirstOrDefault(),Textbox);
If Not txt Is Nothing Then txt.Text = dr.Item("subject_name").ToString
cnt += 1
End While
dr.Close()

Vb.Net Filter Datagridview using combo box

i am having trouble im using visual studio in my other windows form same code it is working properly but i am using it now on another form and it doesn't filter anymore i don't know why.
I am trying to display a list in datagrid view and filter it using two combobox.
Here is a example database of the subject:
-------------------------------------------------------------------------------
|subject_id|subject_name|subject_code|subject_units| sem |year_level
------------------------------------------------------------------------------
| 1 | MATH | Math101 | 3 |First Semester | First Year
| 2 | English | ENG101 | 3 |First Semester | First Year
| 3 | Prgrming | IT101 | 3 |Second Semester| First Year
| 4 | Networking| IT203 | 3 |Second Semester| First Year
Here is my code.
myconn = New MySqlConnection
myconn.ConnectionString = connstring
myconn.Open()
tables = ds.Tables
ds = New DataSet
tables = ds.Tables
Dim Query As String
Query = "selct * from subject_bsit"
'*** CHECKING IF ALL REQUIRED FIELDS ARE PRESENT *****
If ComboBox1.Text = "" Or ComboBox2.Text = "" Then
MessageBox.Show("Complete all fields.")
Exit Sub
End If
If (ComboBox1.Text = "All") And (ComboBox2.Text = "First Semester") Then
da = New MySqlDataAdapter("Select subject_id as 'ID',subject_name as 'SUBJECT',subject_code as 'SUBJECT CODE',subject_units as 'UNITS',sem as 'Semester',year_level as 'YEAR LEVEL' from subject_bsit where sem = '" + ComboBox2.Text + "' or year_level = '" + ComboBox1.Text + "' ", myconn)
da.Fill(ds, "subject_bsit")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
End If
As you can see in the sample image the results must be
All year Level First year to Fourth year but only ALL First Semester subject
but in the picture it also show the Second semester.
It makes me confuse because i have the exact same code in other form but it is working properly. Please help thank you so much.
You just need to replace the logical operator “or” with “and” in your sql string like this way:
from subject_bsit where sem = '" + ComboBox2.Text + "' and year_level = '" + ComboBox1.Text + "' ", myconn)
I hope this can help you bro, ^_^
Restarting Visual Studio solves the problem.

Primary Key for record appearing in textbox where Control Source is not PK field

I'm having a problem with an Access 2010 database where the Primary Key of a new record is also being added to a non-related field when I move to another control on the linked form.
My minimal database consists of a single table called Teams. There are four fields in the table:
+-----------------+-----------+-----------+--------------+
| TeamID | TeamName | CostCode | SortOrder |
+-----------------+-----------+-----------+--------------+
| AutoNumber (PK) | Text(255) | Text(255) | Long Integer |
+-----------------+-----------+-----------+--------------+
This table is linked by the Record Source to a form called Edit_Teams.
There are three controls on the form:
+-----------------+-------------+-----------+------------------------------------+
| Control: | TextBox | TextBox | ComboBox |
+-----------------+-------------+-----------+------------------------------------+
| Name: | txtCostCode | txtTeamID | cmbTeamName |
| Control Source: | CostCode | TeamID | - |
| Row Source: | - | - | SELECT TeamID, TeamName FROM Teams |
+-----------------+-------------+-----------+------------------------------------+
The combobox is bound to column 1, Limit To List = Yes
The form has some code to keep the combobox in sync with the rest of the form when you move between records:
Private Sub Form_Current()
If Not IsNull(Me.txtTeamID) Then
Me.cmbTeamName.Requery
Me.cmbTeamName = Me.txtTeamID
If Me.cmbTeamName <> 0 Then
'Some other code that adds stuff to a subform.
Me.Refresh
End If
Else
Me.cmbTeamName = 0
End If
End Sub
The combobox has two events:
Private Sub cmbTeamName_AfterUpdate()
If Me.cmbTeamName = "0" Then
DoCmd.GoToRecord , , acNewRec
Else
GoToBookmark Me, "TeamID", cmbTeamName
If cmbTeamName <> 0 Then
'Some other code that adds stuff to a subform.
Me.Refresh
End If
End If
End Sub
and
Private Sub cmbTeamName_NotInList(NewData As String, Response As Integer)
With DoCmd
.SetWarnings False
If MsgBox("Add '" & NewData & "' as a new team?", vbYesNo + vbQuestion) = vbYes Then
.RunSQL "INSERT INTO Teams(TeamName, CostCode, SortOrder) " & _
"VALUES ('" & NewData & "', Null," & DCount("TeamID", "Teams") + 1 & ")"
Response = acDataErrAdded
Me.cmbTeamName = Me.cmbTeamName.ItemData(0) 'Move to an item that exists so Requery doesn't fire NotInList.
Me.Requery
GoToBookmark Me, "TeamName", NewData
Me.cmbTeamName.Requery
Me.cmbTeamName = DLookup("TeamID", "Teams", "TeamName='" & TeamName & "'")
Me.txtCostCode.SetFocus
Else
Response = acDataErrContinue
Me.cmbTeamName.Undo
End If
.SetWarnings True
End With
End Sub
There's also this which is used within the previous procedures:
Public Sub GoToBookmark(frm As Form, FieldName As String, FieldValue As String)
Dim rst As DAO.Recordset
Dim rst_Type As Long
On Error GoTo ERR_HANDLE
Set rst = frm.RecordsetClone
FieldName = "[" & FieldName & "]"
Select Case rst.Fields(FieldName).Type
Case 4 'dbLong
rst.FindFirst FieldName & "=" & FieldValue
Case 10 'dbText
rst.FindFirst FieldName & "='" & FieldValue & "'"
End Select
If Not (rst.BOF And rst.EOF) Then
frm.Recordset.Bookmark = rst.Bookmark
End If
rst.Close
EXIT_PROC:
Set rst = Nothing
On Error GoTo 0
Exit Sub
ERR_HANDLE:
'Commented out so I don't have to post the DisplayError procedures.
'DisplayError Err.Number, Err.Description, "mdl_GoToBookMark.GoToBookmark()"
Resume EXIT_PROC
End Sub
The problem:
When I type a new team name into the combobox it asks whether I want to add it to the team list, it then adds the team and moves me to the CostCode textbox where I can type in a cost code if available.
If a cost code isn't available the control should remain blank, but when I move to another control or record (i.e the control loses the focus) then the Primary Key for that record appears in the CostCode textbox and is saved when I change records (losing focus just puts it in the textbox, it doesn't appear in the table until the record is saved).
Your problem lies in the following line:
Response = acDataErrAdded
This line triggers Access to set the field that has focus equal to the value you just added as soon as it loses focus. Because you change focus to a different field, you get this weird behaviour.
Change it for Response = acDataErrContinue (that basically tells Access to not care about what you entered, and lets you handle it yourself) and your code should behave as expected.

Concatenation of multiple entries in one row

I am trying to concatenate a list of attributes for same products which are in different rows.
For example:
Column A (fruit_name) has fruit names and Column B (fruit_colors) has colors.
I want fruit color on the same row as the fruit.
|**fruit_name** | **fruit_colors** |
|----------------|------------------|
|Apple |Red |
|Apple |Yellow |
|Apple |Green |
|Apple |White |
|Banana |Red |
|Banana |Yellow |
|Banana |Green |
|Banana |White |
|Plum |White |
|Plum |Bluish |
|Plum |Purple |
The result should be:
|**name** | **colors** |
|----------------|---------------------------|
|Apple | Red, Yellow, Green, White |
|Banana | Red, Yellow, Green, White |
|Plum | White, Bluish, Purple |
This is what I have:
Set fruit_name = rstsource.Fields("fruits")
Set source_fruit = rstsource.Fields("fruits_list_type")
rstsource.MoveFirst
count = rstsource.RecordCount
counter = 0
fruit_name = source_fruit
result = source_table
Do
Do
counter = counter + 1
result = result & ", " & source_table
rstsource.MoveNext
Loop Until counter = count Or fruit_name <> source_fruit
rstdest.AddNew
rstdest.Fields("names") = fruit_name
rstdest.Fields("colors") = result
rstdest.Update
fruit_name = source_fruit
result = " "
Loop Until rstsource.EOF
This is the result - Some has comma on the front.
Banana - White, White
Apple - ,Yelow, Red
Banana- ,Red
Banana - White, White
Apple , Green
Plum - ,Green
Plum - ,Red
Banana - ,Red
At the end there is a
Run time error 3021.
I would have a read and download of Allen Browne's Concat function http://allenbrowne.com/func-concat.html - It will do exactly what you want.
This will be for report or display purposes only - you shouldn't store the data like this.
How to create this query to combine values?
I have a table with the following structure and values:
EventID PersonName
----------- ------------
1 John
1 Peter
1 Sylvia
2 John
2 Sylvia
3 Peter
3 June
I'd like to run a query and get results in the following format:
EventID PersonNames
-------- ---------------
1 John, Peter, Sylvia
2 John, Sylvia
3 Peter, June
Is there a query that will accomplish this?
Concatenate fields in same table
Author(s) Dev Ashish
(Q) I need to concatenate a field in the format "Value1; Value2; Value3" etc. for each unique value of another field in the same table. How can I do this?
(A) Using the fConcatFld function, in the Northwind database, the following query should return a concatenated list of all CustomerIDs if you group by ContactTitle.
SELECT ContactTitle, fConcatFld("Customers","ContactTitle","CustomerID","string",[ContactTitle]) AS CustomersFROM CustomersGROUP BY ContactTitle;
'************ Code Start **********
'This code was originally written by Dev Ashish
'It is not to be altered or distributed,
'except as part of an application.
'You are free to use it in any application,
'provided the copyright notice is left unchanged.
'
'Code Courtesy of
'Dev Ashish
'
Function fConcatFld(stTable As String, _
stForFld As String, _
stFldToConcat As String, _
stForFldType As String, _
vForFldVal As Variant) _
As String
'Returns mutiple field values for each unique value
'of another field in a single table
'in a semi-colon separated format.
'
'Usage Examples:
' ?fConcatFld(("Customers","ContactTitle","CustomerID", _
' "string","Owner")
'Where Customers = The parent Table
' ContactTitle = The field whose values to use for lookups
' CustomerID = Field name to concatenate
' string = DataType of ContactTitle field
' Owner = Value on which to return concatenated CustomerID
'
Dim lodb As Database, lors As Recordset
Dim lovConcat As Variant, loCriteria As String
Dim loSQL As String
Const cQ = """"
On Error GoTo Err_fConcatFld
lovConcat = Null
Set lodb = CurrentDb
loSQL = "SELECT [" & stFldToConcat & "] FROM ["
loSQL = loSQL & stTable & "] WHERE "
Select Case stForFldType
Case "String":
loSQL = loSQL & "[" & stForFld & "] =" & cQ & vForFldVal & cQ
Case "Long", "Integer", "Double": 'AutoNumber is Type Long
loSQL = loSQL & "[" & stForFld & "] = " & vForFldVal
Case Else
GoTo Err_fConcatFld
End Select
Set lors = lodb.OpenRecordset(loSQL, dbOpenSnapshot)
'Are we sure that duplicates exist in stFldToConcat
With lors
If .RecordCount <> 0 Then
'start concatenating records
Do While Not .EOF
lovConcat = lovConcat & lors(stFldToConcat) & "; "
.MoveNext
Loop
Else
GoTo Exit_fConcatFld
End If
End With
'That's it... you should have a concatenated string now
'Just Trim the trailing ;
fConcatFld = Left(lovConcat, Len(lovConcat) - 2)
Exit_fConcatFld:
Set lors = Nothing: Set lodb = Nothing
Exit Function
Err_fConcatFld:
MsgBox "Error#: " & Err.Number & vbCrLf & Err.Description
Resume Exit_fConcatFld
End Function
'************ Code End **********
Copy and paste the fConcatFld( ) function into a code module. Change the
following VBA line of code:
lovConcat = lovConcat & lors(stFldToConcat) & "; "
to:
lovConcat = lovConcat & lors(stFldToConcat) & ", "
... then save it and compile the code.
Next, create a new query and open the query in SQL View and paste the
following SQL statement into the SQL View pane:
SELECT EventID, fConcatFld("MyTable","EventID","PersonName","Long", EventID)
AS PersonNames
FROM MyTable
GROUP BY EventID;
... and replace "MyTable" with the name of your table. If the "EventID"
data type isn't Long, then you'll need to replace this in the SQL statement,
too, with whatever data type your field is using.
Save and run the query. Voila! Comma separated list.

Issues with adding to a database

My program has a method for adding dictionaries through a text file to the database. Said text file consists of a word, what manner of word it is (i.e. noun, verb, etc.) and then the associated image's file name, all formatted in the form of:
word#type#filename
word2#type#filename2
and so on. To avoid repeats of word entries, I use a MySqlDataReader in conjunction with a query to run through all of the rows and then add any rows that are not yet added. The code looks like this:
Private Sub btnCreateBank_Click(sender As Object, e As EventArgs) Handles btnCreateBank.Click
Dim newOpenDialog As New OpenFileDialog
Dim newFileStream As FileStream = Nothing
newOpenDialog.InitialDirectory = GetFolderPath(SpecialFolder.MyDocuments)
newOpenDialog.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
newOpenDialog.FilterIndex = 1
newOpenDialog.ShowDialog()
Try
newFileStream = newOpenDialog.OpenFile()
If (newFileStream IsNot Nothing) Then
Dim sr As New StreamReader(newFileStream)
Dim fileContents As String = sr.ReadToEnd()
Dim fileContentsArray() As String = Split(fileContents, vbNewLine)
Dim fullSplitArray As New List(Of String)
For i As Integer = 0 To fileContentsArray.Length - 1
fullSplitArray.AddRange(Split(fileContentsArray(i).ToString, "#"))
Next
For j As Integer = 0 To fullSplitArray.Count - 1 Step 3
Dim connString As String = "server=localhost;user=root;database=jakub_project;port=3306;password=password;"
Try
Using conn As New MySqlConnection(connString)
conn.Open()
Dim command As New MySqlCommand("SELECT COUNT(word) FROM words WHERE word=#inputWord", conn)
command.Prepare()
command.Parameters.AddWithValue("#inputWord", fullSplitArray.Item(j))
Dim dataReader As MySqlDataReader = command.ExecuteReader()
While dataReader.Read()
If dataReader.Item(0) = 1 Then
MsgBox(fullSplitArray.Item(j) & " added to system.")
Else
Using conn2 As New MySqlConnection(connString)
conn2.Open()
Dim addCmd As New MySqlCommand("INSERT INTO words(word, wordType, wordFilename) VALUES(#inputWord, #inputType, #inputFilename);", conn2)
addCmd.Prepare()
addCmd.Parameters.AddWithValue("#inputWord", fullSplitArray.Item(j))
addCmd.Parameters.AddWithValue("#inputType", fullSplitArray.Item(j + 1))
addCmd.Parameters.AddWithValue("#inputFilename", fullSplitArray.Item(j + 2))
addCmd.ExecuteNonQuery()
MsgBox(fullSplitArray.Item(j) & " added to system.")
conn2.Close()
End Using
End If
End While
dataReader.Close()
conn.Close()
End Using
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try
Next
End If
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try
End Sub
A prior variant in which I did not include the second connection had given me the right result the first time, adding in eight rows. However, all successive attempts gave out errors that stem from what is supposedly a lack of that second connection. But now, all attempts with this subroutine output a table like this.
+--------+----------------------+----------------------+--------------------------+
| wordID | word | wordType | wordFilename |
+--------+----------------------+----------------------+--------------------------+
| 1 | acorn | noun | acorn.jpg |
| 2 | beach | noun | beach.jpg |
| 3 | chicken | noun | chicken.jpg |
| 4 | dance | verb | dance.jpg |
| 5 | elbow | noun | elbow.gif |
| 6 | fight | verb | fight.gif |
| 7 | grow | verb | grow.jpg |
| 8 | hat | noun | hat.jpg |
| 11 | acorn noun acorn.jpg | beach noun beach.jpg | chicken noun chicken.jpg |
| 12 | dance verb dance.jpg | elbow noun elbow.jpg | fight verb fight.gif |
+--------+----------------------+----------------------+--------------------------+
What I want is for the data to be loaded as seen in the first set of rows, rather than what I am now receiving in the bottom two. But I am unsure where the source of the problem lay.
The error messages don't really tell me what is going on, either. The first error message to appear tells me that the data is too long for the column it is attempting to insert it into. The second error tells me that the integer j in my For loop is out of bounds, which is occurring now because of the system seeming to read the whole string rather than three substrings.
If I am understanding you properly,
To me it looks like there was a possible flaw in your text file splitting sequence. Which is not noticeable in your posted code because you may have corrected the error after finding it?
As for the errors...
The first error is telling you that the data for the field in question (you did not mention which field it was) is too big to field into the allocated space. This too can be quantified as being caused by incorrect splitting
in your splitting sequence.
As for the second error it is unclear but I would assume do not get that error after you corrected the splitting issue?
Finally, it is recommended to move your Command.Prepare so it comes AFTER you have added all your command parameters.
Conclusion After Your Extra Info
After reading your comments below, I was still of the mind that the initial cause of the problems were in your splitting routine.
After use the watch tool to look at the splitting results, it was obvious what was happening. You can see the watch window below
Further more it seems to make more sense to have two separate routines for checking if the word exists and to add a new word if it doesn't exist.
By separating them out of your main processing block it makes it a lot easier to see what is going on...
So I have done that and tested it and it seems to work fine.
The main difference is that I skipped the step where you are reading in a data file and kind of simulated the contents of the in a string....
Private Sub btnCreateBank_Click(sender As Object, e As EventArgs) Handles btnCreateBank.Click
'
Dim counta As Integer = 0
Dim fullSplitArray As New List(Of String)
Dim fileContents As String = ""
Dim fileContentsArray() As String
Dim tmpWord As String = Nothing
Dim tmpType As String = Nothing
Dim tmpFile As String = Nothing
Dim Test As Boolean = False
'
Try
fileContents = "1#acorn#noun#acorn.jpg" & vbNewLine & "2#beach#noun#beach.jpg" & vbNewLine & "3#chicken#noun#chicken.jpg" & vbCrLf & "4#dance#verb#dance.jpg" & vbNewLine & "5#elbow#noun#elbow.gif" & vbNewLine & "6#fight#verb#fight.gif" & vbNewLine & "7#grow#verb#grow.jpg" & vbNewLine & "8#hat#noun#hat.jpg"
fileContentsArray = Split(fileContents, vbNewLine)
For i As Integer = 0 To fileContentsArray.Length - 1
fullSplitArray.AddRange(Split(fileContentsArray(i).ToString, "#"))
Next
For j As Integer = 0 To fullSplitArray.Count - 1 Step 4
Test = False
Try
Test = IsWordAlreadyListed(fullSplitArray(j + 1), tmpWord, tmpType, tmpFile)
If Test Then
MsgBox(fullSplitArray.Item(j + 1) & " already listed in system (" & Trim(tmpWord) & ", " & Trim(tmpType) & ", " & Trim(tmpFile) & ")")
Else
Test = AddNewRow(fullSplitArray(j + 1), fullSplitArray(j + 2), fullSplitArray(j + 3))
End If
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try
Next
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
End Try
Test = Nothing
'
End Sub
Function IsWordAlreadyListed(ByVal ParamWord As String, ByRef pRtnWord As String, ByRef pRtnType As String, ByRef pRtnFile As String) As Boolean
'
'-> Locals
Dim iwalConn As Data.SqlClient.SqlConnection = Nothing
Dim iwalCmd As Data.SqlClient.SqlCommand = Nothing
Dim iwalAdapter As Data.SqlClient.SqlDataReader = Nothing
Dim iwalQuery As String = Nothing
'-> Init
IsWordAlreadyListed = False
iwalConn = New System.Data.SqlClient.SqlConnection()
iwalConn.ConnectionString = "YOUR-CONNECTION-STRING-HERE"
'-> Process Request
If Trim(paramword) <> "" Then
iwalQuery = "SELECT * FROM words WHERE word='" & Trim(ParamWord) & "'"
'-> Query Databanks
iwalCmd = New Data.SqlClient.SqlCommand(iwalQuery, iwalConn)
If iwalCmd.Connection.State = Data.ConnectionState.Closed Then iwalCmd.Connection.Open()
iwalAdapter = iwalCmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
If iwalAdapter.HasRows Then
iwalAdapter.Read()
pRtnWord = iwalAdapter.GetValue(iwalAdapter.GetOrdinal("word"))
pRtnType = iwalAdapter.GetValue(iwalAdapter.GetOrdinal("wordType"))
pRtnFile = iwalAdapter.GetValue(iwalAdapter.GetOrdinal("wordFilename"))
IsWordAlreadyListed = True
End If
If iwalCmd.Connection.State = Data.ConnectionState.Open Then iwalCmd.Connection.Close()
Else
MsgBox("Error: Invalid or missing word parameter!")
End If
'-> tidy up
iwalCmd = Nothing
iwalAdapter = Nothing
iwalQuery = Nothing
iwalConn = Nothing
'
End Function
Function AddNewRow(ByVal ParamWord As String, ByVal ParamType As String, ParamFile As String) As Boolean
'
AddNewRow = False
Dim arnConn As System.Data.SqlClient.SqlConnection = Nothing
Dim arnConnString As String = "YOUR CONNECTION STRING HERE"
arnConn = New System.Data.SqlClient.SqlConnection(arnConnString)
arnConn.Open()
Try
Using arnConn
Dim addCmd As New System.Data.SqlClient.SqlCommand("INSERT INTO words(word, wordType, wordFilename) VALUES(#inputWord, #inputType, #inputFilename);", arnConn)
addCmd.Parameters.AddWithValue("#inputWord", ParamWord)
addCmd.Parameters.AddWithValue("#inputType", ParamType)
addCmd.Parameters.AddWithValue("#inputFilename", ParamFile)
'addCmd.Prepare()
addCmd.ExecuteNonQuery()
MsgBox(ParamWord & " added to system.")
AddNewRow = True
End Using
Catch ex As Exception
MsgBox("Error: " & ex.ToString())
Finally
arnConn.Close()
End Try
End Function