Database locked in vb.net when trying to update data in vb.net - vb.net

Hello I have a simple method to update customer details in one of my database tables however when i try to update it an error occurs saying the database is locked. I have no idea how to fix this because my add and delete queries work just fine.
This is the error message:
System.Data.SQLite.SQLiteException: 'database is locked
database is locked'
Public Sub updateguest(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN UPDATED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Dim usql As String = "UPDATE Customers SET fname = '" & txtFName.Text & "'" & "WHERE CustomerID ='" & txtSearchID.Text & "'"
updateguest(usql)
End Sub
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
Dim msql, msql1 As String
Dim con As New SQLiteConnection(ConnectionString)
con.Open()
msql = "SELECT * FROM Customers Where Fname Like '" & txtSearchName.Text & "%'"
msql1 = "SELECT * FROM Customers Where CustomerID '" & txtSearchID.Text & "'"
Dim cmd As New SQLiteCommand(msql, con)
Dim cmd1 As New SQLiteCommand(msql1, con)
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
Dim mdr As SQLiteDataReader = cmd.ExecuteReader()
If mdr.Read() Then
If txtSearchName.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE fname LIKE'" & txtSearchName.Text & "%'"
Dim con1 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con1)
con1.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con1.Close()
txtSearchID.Clear()
ElseIf txtSearchID.Text <> "" Then
sSQL = "SELECT * FROM customers WHERE CustomerID ='" & txtSearchID.Text & "'"
Dim con2 As New SQLiteConnection(ConnectionString)
Dim cmd2 As New SQLiteCommand(sSQL, con2)
con2.Open()
Dim da As New SQLiteDataAdapter(cmd2)
da.Fill(newds, "customers")
newdt = newds.Tables(0)
If newdt.Rows.Count > 0 Then
ToTextbox(newdt)
End If
dgvCustomerInfo.DataSource = newdt
con2.Close()
txtSearchName.Clear()
End If
Else
MsgBox("No data found")
End If
End Sub
Private Sub IbtnDelete_Click(sender As Object, e As EventArgs) Handles ibtnDelete.Click
Dim dsql As String = "DELETE FROM customers WHERE customerid = " & txtSearchID.Text & ""
deleteme(dsql)
updatedgv(dgvCustomerInfo)
txtSearchID.Clear()
txtSearchName.Clear()
End Sub
Public Sub deleteme(ByVal sql As String)
Try
con.Open()
With cmd
.CommandText = sql
.Connection = con
End With
result = cmd.ExecuteNonQuery
If result > 0 Then
MsgBox("NEW RECORD HAS BEEN DELTED!")
con.Close()
Else
MsgBox("NO RECORD HASS BEEN DELTED!")
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub

You made a good start on keeping your database code separate from you user interface code. However, any message boxes should be shown in the user interface and any sql statements should be written in the data access code.
I used Using...End Using blocks to ensure that database objects are closed and disposed. I used parameters to protect against sql injection. I am not too sure of the mapping of DbType types to Sqlite types. You might have to fool with that a bit. In you original Update statement you had the ID value in quotes. This would pass a string. When you use parameters, you don't have to worry about that or ampersands and double quotes. Just one clean string.
Private ConStr As String = "Your connection string"
Public Function updateguest(FirstName As String, ID As Integer) As Integer
Dim Result As Integer
Dim usql As String = "UPDATE Customers SET fname = #fname WHERE CustomerID = #ID;"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(usql, con)
cmd.Parameters.Add("#fname", DbType.String).Value = FirstName
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
con.Open()
Result = cmd.ExecuteNonQuery
End Using
Return Result
End Function
Private Sub IbtnUpdate_Click(sender As Object, e As EventArgs) Handles ibtnUpdate.Click
Try
Dim Result = updateguest(txtFName.Text, CInt(txtSearchID.Text))
If Result > 0 Then
MsgBox("New RECORD HAS BEEN UPDATED!")
Else
MsgBox("NO RECORD HAS BEEN UPDATDD!")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

Related

Using 2 combo boxes to populate a datagridview in VB.NET

I having problems understanding why my one of my comboboxes displays a filtered search but the other one doesn't, I am using the same code for both comboboxes but modified some SQL queries linked to my database. I have also noticed that when I remove or comment out the code for any one of the comboboxes the the filtered search happens for the one hasn't been commented or removed. I also used an "If, Else" statement but still doesn't work. I would also want for both comboboxes to be used to filter a datagridview. Just to keep in mind once the item is selected from the combobox a search button is pressed to filer/display data into the datagridview.
Kind Regards
Here is my code and form:
[Redundant Data being displayed] https://i.stack.imgur.com/JEQI4.png
[ComboBox Brand works as intended] https://i.stack.imgur.com/6YyBf.png
[ComboBox Category displays everything rather than displaying the category chosen] https://i.stack.imgur.com/oEfII.png
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
If Not CmbBrand.SelectedIndex & CmbCategory.SelectedIndex = Nothing Then
BrandDisplay()
ElseIf CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
CategoryDisplay()
ElseIf Not CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
End If
cn.Close()
End Sub
Private Sub BrandDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STBrand Like #BrandSearch"
.Parameters.AddWithValue("#BrandSearch", "%" & CmbBrand.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Brand from the drop down list", "Brand", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
Private Sub CategoryDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
```
It is a good idea to separate your User Interface code from you database code. Your event procedure code should be rather brief.
Declare your Connections, Commands and DataReaders in the method where they are used so they can be disposed. Using...End Using blocks do this for us; they also close the connection. Pass your connection string directly to the constructor of the connection.
We have a different CommandText and ParametersCollection for each possibility. For Sql Server use the Add method rather than AddWithValue.
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dt = GetSearchData(CmbBrand.Text, CmbCategory.Text)
DGVRecord.DataSource = dt
End Sub
Private Function GetSearchData(Brand As String, Category As String) As DataTable
Dim dt As New DataTable
Dim sqlString = "Select * From From TblStock "
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If Not String.IsNullOrEmpty(Brand) AndAlso Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch And STBrand = #BrandSearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Brand) Then
cmd.CommandText = sqlString & "Where STBrand = #BrandSearch;"
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
Else
cmd.CommandText = sqlString & ";"
End If
cn.Open()
Using reader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Return dt
End Function
For better understanding you need to change those first "if... then... else...".
If the combobox is not selected it will have value -1 so you can do it like this:
Dim bBrandIsSelected as boolean = CmbBrand.SelectedIndex <> -1
Dim bCategoryIsSelected as boolean = CmbCategory.SelectedIndex <> -1
Now you can build the code more easily like:
If bBrandIsSelected AndAlso bCategoryIsSelected then
' do something
else
if bBrandIsSelected then
BrandDisplay()
else
if bCategoryIsSelected then
CategoryDisplay()
End if
End if
End if

vb.net message: no value given for one or more required parameters

I made a POS project but when i save the data to access database the error is shown:
no value given for one or more required parameters.
My code is:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim MyConnection As OleDb.OleDbConnection = Nothing
Dim MyTransaction As OleDb.OleDbTransaction = Nothing
Try
'create the connection and transaction object
MyConnection = New OleDb.OleDbConnection(My.Settings.dbConnectionString)
MyConnection.Open()
MyTransaction = MyConnection.BeginTransaction
'insert the new recipt
Dim SQL As String = "insert into recipts (ReciptDate, ReciptTotal) values (:0,:1)"
Dim CMD1 As New OleDb.OleDbCommand
CMD1.Connection = MyConnection
CMD1.Transaction = MyTransaction
CMD1.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", Now.Date)
CMD1.Parameters.AddWithValue(":1", TextBox4.Text)
CMD1.ExecuteNonQuery()
CMD1.Dispose()
'get the id for the recipt
SQL = "Select max (reciptId) as MAXID from recipts"
Dim CMD2 As New OleDb.OleDbCommand
CMD2.Connection = MyConnection
CMD2.Transaction = MyTransaction
CMD2.CommandText = SQL
Dim ReciptID As Long = CMD2.ExecuteScalar()
CMD2.Dispose()
'insert the details of the recipt
Dim I As Integer
For I = 0 To DGV2.Rows.Count - 1
'get the values
Dim Barcode As String = DGV2.Rows(I).Cells(0).Value
Dim BuyPrice As Decimal = DGV2.Rows(I).Cells(2).Value
Dim SellPrice As Decimal = DGV2.Rows(I).Cells(3).Value
Dim ItemCount As Integer = DGV2.Rows(I).Cells(4).Value
'next create a command
Dim CMD3 As New OleDb.OleDbCommand
SQL = "insert into ReciptDetails" & _
"(ReciptId, Barcode,ItemCount,ItemBuyPrice,ItemSellPrice)" & _
"Values" & _
"(:0 ,:1 ,:2 ,:3 ,:4)"
CMD3.Connection = MyConnection
CMD3.Transaction = Mytransaction
CMD3.CommandText = SQL
CMD1.Parameters.AddWithValue(":0", ReciptID)
CMD1.Parameters.AddWithValue(":1", Barcode)
CMD1.Parameters.AddWithValue(":2", ItemCount)
CMD1.Parameters.AddWithValue(":3", BuyPrice)
CMD1.Parameters.AddWithValue(":4", SellPrice)
CMD3.ExecuteNonQuery()
CMD3.Dispose()
Next
'all well save the changes
Mytransaction.Commit()
'close conncetion
Mytransaction.Dispose()
MyConnection.Close()
MyConnection.Dispose()
DGV2.Rows.Clear()
TextBox4.Text = ""
Catch ex As Exception
If Mytransaction IsNot Nothing Then
Mytransaction.Rollback()
End If
If MyConnection IsNot Nothing Then
If MyConnection.State = ConnectionState.Open Then
MyConnection.Close()
End If
End If
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
What is the problem here?
Simple typo. In your CMD3 you're adding all the parameters to CMD1
Hence CMD3 has 5 missing parameters.

Comparing TimeoftheDay to a String

Error in Comparing Time to a String
Cdate is my previous code and i revise it to compareTime Can anyone
help me if the current expression to compare time is correct because
the message is "Contact your Administrator! Maybe your not
registered."
So the expression is still "false"
#Region "TIMER"
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
LBLDATE.Text = My.Computer.Clock.LocalTime.Date
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
LBLTIME.Text = TimeOfDay
End Sub
#End Region
Dim conn As OleDb.OleDbConnection = GetConnection()
Dim sql As String
Dim sql1 As String
Dim A As Integer
Dim result = Nothing
Dim compareTime As String = "7:01:00 PM"
' Dim amlate1 As String = "7:01:00 PM"
Dim remm1 As String
' If CDate(Form7TO3.LBLTIME.Text) >= CDate(amlate1) Then
If compareTime = DateTime.Now.ToString("h:mm:ss tt") Then
remm1 = "LATE"
Else
remm1 = "ON TIME"
End If
Try
sql1 = "SELECT * FROM DTR_REC WHERE MEM_CODES LIKE '" & Form7TO3.txtinput.Text & "' AND SDATE = '" & Form7TO3.LBLDATE.Text & "'"
Dim DA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql1, conn)
Dim DS As New DataSet
DA.Fill(DS, "dtrdb")
A = DS.Tables("dtrdb").Rows.Count
If A > 0 Then
MessageBox.Show("Sorry you Already finished Log in!")
Else
sql = "INSERT INTO DTR_REC (MEM_CODES, AM_IN, FIRST_AM_REMARK, SDATE) VALUES (#MEM_CODES, #AM_IN, #FIRST_AM_REMARK, #SDATE)"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDb.OleDbParameter("#MEM_CODES", Form7TO3.txtinput.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter(" #AM_IN", Form7TO3.LBLTIME.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter("#FIRST_AM_REMARK", remm1))
cmd.Parameters.Add(New OleDb.OleDbParameter("#SDATE", DateTime.Parse(Form7TO3.LBLDATE.Text)))
conn.Open()
cmd.ExecuteNonQuery()
If remm1 = "LATE" Then
MessageBox.Show("Hurry up your Late")
ElseIf remm1 = "ON TIME" Then
MessageBox.Show("Very good you come on time!")
End If
End If
clear()
Catch ex As Exception
Dim dgresult As DialogResult
Dim ms As String
ms = "Contact your Administrator! Maybe your not registered."
MessageBox.Show(ms, "Error in connection", MessageBoxButtons.OKCancel, _
MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2)
If dgresult = DialogResult.Yes Then
Form1.Show()
End If
End Try
Return result
Here's my current codes
Can anyone revise this codes
If the record is already exist a messagebox will appear saying "Sorry you finished log in"
otherwise it will save/add records on my database
(The problem is , if the records still exists it add/insert another the same record)
Dim conn As OleDb.OleDbConnection = GetConnection()
Dim sql As String
Dim sql1 As String
'Dim A As Integer
Dim result = Nothing
'Dim time_1 As String = DateTime.Parse("11:00:00 PM").ToString("T")
'Dim time_2 As String = DateTime.Now.ToString("T")
Dim remm1 As String
Dim PMOUT As String = "11:00:00 PM"
Dim str As String = "HH:mm:ss"
str = TimeOfDay()
' If DateTime.Now.TimeOfDay > amlate1.TimeOfDay Then
' If DateTime.Compare(time_1, time_2) > 0 Then
If str >= PMOUT Then
remm1 = "LATE"
Else
remm1 = "ON TIME"
End If
Try
conn.Open()
sql1 = "SELECT * FROM DTR_REC WHERE MEM_CODES = '" & Form11TO7.txtinput.Text & "' AND SDATE = #" & FormatDateTime(DateTime.Now, DateFormat.GeneralDate = DateFormat.ShortDate) & "#"
' Dim DA As OleDb.OleDbDataAdapter = New OleDb.OleDbDataAdapter(sql1, conn)
Dim cmd1 As New OleDb.OleDbCommand(sql1, conn)
'Dim DS As New DataSet
'DA.Fill(DS, "dtrdb")
'A = DS.Tables("dtrdb").Rows.Count
'If A > 0 Then
Using reader As OleDb.OleDbDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
'user already finished to time in
MessageBox.Show("Sorry you Already finished Log in!")
Else
sql = "INSERT INTO DTR_REC (MEM_CODES, PM_IN, FIRST_PM_REMARK, SDATE) VALUES (#MEM_CODES, #PM_IN, #FIRST_PM_REMARK, #SDATE)"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add(New OleDb.OleDbParameter("#MEM_CODES", Form11TO7.txtinput.Text))
cmd.Parameters.Add(New OleDb.OleDbParameter(" #PM_IN", str))
cmd.Parameters.Add(New OleDb.OleDbParameter("#FIRST_PM_REMARK", remm1))
cmd.Parameters.Add(New OleDb.OleDbParameter("#SDATE", FormatDateTime(DateTime.Now, DateFormat.GeneralDate = DateFormat.ShortDate)))
Dim icount As String
icount = cmd.ExecuteNonQuery()
MessageBox.Show(icount)
If remm1 = "LATE" Then
MessageBox.Show("Hurry up your Late")
ElseIf remm1 = "ON TIME" Then
MessageBox.Show("Very good you come on time!")
End If
End If
End Using
clear()
Catch ex As Exception
Dim dgresult As DialogResult
Dim ms As String
ms = "Contact your Administrator! Maybe your not registered."
'MessageBox.Show(ms = "Contact your Administrator! Maybe your not registered." & vbNewLine & ex.Message)
MessageBox.Show(ms, "Error in connection", MessageBoxButtons.OKCancel, _
MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2)
If dgresult = DialogResult.Yes Then
Form1.Show()
End If
'MessageBox.Show(ex.Message)
End Try
Return result

Populating Datagrid

I am creating a pageant scoring system,
I have this functions for populating my datagridview's first column using query:
Public Sub searchContestant()
If comboCategory.SelectedIndex <> 0 Then
Dim id As Integer = Login.JudgeBindingSource1.Current("Cont_id")
Dim critID As Integer = Convert.ToInt32(lblID.Text)
'search the contest record by the contest_id
Dim con As New SqlConnection
Dim reader As SqlDataReader
Dim reader2 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
Try
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & critID & "' ", con)
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
' Execute Query
reader = cmd.ExecuteReader()
nc.Name = "Contestants"
nc.Width = 250
nc.ReadOnly = True
DataGridView1.Columns.Add(nc)
While reader.Read()
nc = New DataGridViewTextBoxColumn
nc.Name = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.HeaderText = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.Width = 150
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
Try
'populate contestant rows
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
reader2 = cmd2.ExecuteReader()
While reader2.Read()
nc = New DataGridViewTextBoxColumn
nc.Width = 100
DataGridView1.Rows.Add(reader2.GetString(2).ToString())
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End If
End Sub
And for succeeding columns :
Public Sub searchCriteria()
Dim con As New SqlConnection
Dim reader4 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
Try
'populate Criteria
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & lblID.Text & "' ", con)
con.Open()
reader4 = cmd.ExecuteReader
While reader4.Read
nc = New DataGridViewTextBoxColumn
nc.Name = reader4.GetString(1).ToString & Chr(13) & reader4.GetString(2).ToString & "%"
nc.Width = 100
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End Sub
This is the output:
And everytime a judge login, I insert data into the system with this function:
Public Sub makeTransaction()
Dim con2 As New SqlConnection
'get the judge id upon logging in
Dim judgeID = Login.JudgeBindingSource1.Current("Judge_id")
'get the contest id of the judge
Me.JudgeTableAdapter.FillByJudgeID(Me.PSSDataSet.Judge, judgeID)
Dim JudgeContestid = Login.JudgeBindingSource1.Current("Cont_id")
Me.ContestantTableAdapter.FillByContestID(Me.PSSDataSet.Contestant, JudgeContestid)
'get the contestant id
Me.ContestTableAdapter.FillByContestID(Me.PSSDataSet.Contest, JudgeContestid)
Dim contestID As Integer = ContestBindingSource.Current("Cont_id")
'get the category of the contest
Me.CategoryTableAdapter.FillByContestID(Me.PSSDataSet.Category, Convert.ToInt32(contestID))
For Each Category As DataRow In Me.PSSDataSet.Category.Rows
Me.CriteriaTableAdapter.FillByCategoryID(Me.PSSDataSet.Criteria, Category("Cat_id"))
For Each Contestant As DataRow In Me.PSSDataSet.Contestant.Rows
For Each Criteria As DataRow In Me.PSSDataSet.Criteria.Rows
TransactionsTableAdapter.Insert(JudgeContestid, Contestant("Con_id"), Criteria("Cri_id"), 0)
Next
Next
Next
End Sub
Now my problem is, how can I populate the datagrid using the data recently made by MakeTransaction() function?

Child list for field salesreport cannot be created

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdOk.Click
Dim scan As String = "select ProductCode from products where ProductCode = '" & TextBox1.Text & "';"
connection.Open()
Dim cmd = New MySqlCommand(scan, connection)
Dim dr As MySqlDataReader = cmd.ExecuteReader
If dr.Read = True Then
MsgBox("Match found")
connection.Close()
Dim insert As String = "insert into salesreport (ProductName,ProductPrice) select products.ProductName,products.ProductPrice from products where products.ProductCode = '" & TextBox1.Text & "';"
connection.Open()
da = New MySqlDataAdapter(insert, connection)
da.Fill(ds, "salesreport")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "salesreport"
connection.Close()
Else
connection.Close()
MsgBox("No match found")
TextBox1.Text = ""
TextBox1.Select()
End If
End Sub
INSERT statements doesn't return records.
There is no sense in this situation to use a DataAdapter to INSERT a record.
Use the MySqlCommand.ExecuteNonQuery method to insert your record, then read the added row with a MySqlDataAdapter
Also, do not concatenate text, typed by your user, to build and use an sql text for the database engine. Your code could be easily used to create Sql Injection Attacks.
Dim scan As String = "select ProductCode from products " +
"where ProductCode = ?prodCode"
connection.Open()
Dim cmd = New MySqlCommand(scan, connection)
cmd.Parameters.AddWithValue("?prodCode", TextBox1.Text)
..........
Dim insert As String = "insert into salesreport (ProductName,ProductPrice) " +
"select products.ProductName,products.ProductPrice from products " +
"where products.ProductCode = ?prodCode"
cmd = new MySqlCommand(insert, connection)
cmd.Parameters.AddWithValue("?prodCode", TextBox1.Text)
cmd.ExecuteNonQuery()
da = New MySqlDataAdapter(scan, connection)
da.SelectCommand.Parameters.AddWithValue("?prodCode", TextBox1.Text)
da.Fill(ds, "salesreport")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "salesreport"