Populating Datagrid - sql

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?

Related

Database locked in vb.net when trying to update data in 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

SQL Update not updating records in access

Trying to update the values of Comment and ProgressValue inside a table in access. The message box at the end pops up but none of the values are changed.
Sub UpdateWeeklyReport()
Dim con As OleDbConnection
Dim com As OleDbCommand
con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\ProjectDatabase.mdb")
com = New OleDbCommand("Update WeeklyReport Set Comment = #Comment, ProgressValue = #ProgressValue Where [EntryDate]='" & CBDate.SelectedValue.ToString & "' AND [AdminNo]=" & CBAdmin.SelectedValue & " AND [ClassCode]='" & CBClass.SelectedItem.ToString & "'", con)
con.Open()
com.Parameters.Add("#Comment", OleDbType.LongVarChar).Value = txtComment.Text
com.Parameters.Add("#ProgressValue", OleDbType.Integer).Value = CBProgress.Text
com.ExecuteNonQuery()
con.Close()
MessageBox.Show("Report Changed")
intialconnection()
End Sub
End Class

VB.NET:Updating record in Ms Access

I am creating an employee timing sheet in which they have to insert their timings through pressing timein and timeout buttons. For timein I am creating a new record in database, for that person, and for timeout I am using UPDATING command to update that existing record. Here is my code:
Dim cb As New OleDb.OleDbCommandBuilder(ssda)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim str As String
str = "UPDATE emp_timing SET emp_timing.emp_timeout = '" & OnlyTime & "' WHERE (((emp_timing.emp_code)='" & TextBox1.Text & "') AND ((emp_timing.day)=" & Now.ToString("MM/dd/yyyy") & "))"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
Catch ex As Exception
MsgBox(ex.Message)
End Try
My code is working fine but the problem is that it is not updating records in database.
Datatype for fields in Access:
emp_code = Number, emp_timeout = Text, day = Date/Time.
As usual this is caused by your code not using the Parameters collection to pass values to the database engine. This is not really understood until you hit a conversion problem as always happens with dates
str = "UPDATE emp_timing SET emp_timeout = #p1 " & _
"WHERE emp_code = #p2 AND day = #p3"
Using con = new OleDbConnection( dbProvider & dbSource)
Using cmd = New OleDbCommand(str, con)
con.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = OnlyTime
cmd.Parameters.Add("#p2", OleDbType.Integer).Value = Convert.ToInt32(TextBox1.Text)
cmd.Parameters.Add("#p3", OleDbType.Date).Value = new DateTime(Now.Year, Now.Month, Now.Day)
Try
Dim rowsAdded = cmd.ExecuteNonQuery()
if rowsAdded > 0 Then
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using

SQL Error: "There are no rows at position 0"

I am Trying to create a login form for my software and i keep getting this feedback as error; "There are no rows at postion 0".....This happens whenever i try to add a WHERE clause to my (SLELECT ProfileName, ProfilePassword from Profile) query (i.e 'sqlQuery' in code)......This is a snippet of my code
Public Sub sql_login(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'INITIALIZE YOUR COMMANDS
'IT HOLDS THE DATA TO BE EXECUTED
With cmd
'PASS ON THE VALUE OF CON TO THE MYSQL COMMANND WHICH IS THE CONNECTION
.Connection = con
'THE FUNCTION OF THIS IS TO RETURN THE TEXT REPRESENTED BY A COMMAND OBJECT
.CommandText = sqlQuery
End With
Dim dt = New DataTable
'FOR RETRIEVING AND FILLING DATA IN THE TABLE
Dim da = New SqlDataAdapter(sqlQuery, con)
'NEW TABLE IN THE DATATABLE
da.Fill(dt)
con.Close()
'SET THE TOTAL ROWS OF THE TABLE IN A VARIABLE[MAXROWS]
Dim maxrows As Integer = dt.Rows.Count
con.Close()
'preventing non empty values
If Loginform.UsernameTextBox.Text <> "" And Loginform.PasswordTextBox.Text <> "" Then
If dt IsNot Nothing Then
'CHECKING IF THE TOTAL ROWS OF THE TABLE ARE GREATER THAN 0
If maxrows > 0 Then
'THIS WILL BE NOTIFY YOU THAT WHO WOULD BE THE USER'S
MessageBox.Show("Welcome " & dt.Rows(1).Item(0) & "!" & ControlChars.NewLine & "You have sucessfully logged in.", "Login Confirmation")
'Tracing login time
Try
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "INSERT INTO ProfileDates (ProfileName, LoginDates, ProfileID) VALUES ('" & Loginform.UsernameTextBox.Text & "',GetDate(),( SELECT TOP 1 profileID FROM Profile where ProfileName = '" & Loginform.UsernameTextBox.Text & "') )"
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Suppliers_Module.LogoutBtn.Enabled = True
Suppliers_Module.LoginButton.Enabled = False
Catch ex As Exception
con.Close()
MessageBox.Show(ex.Message)
End Try
end if
end if
end if
counting on you for your help. Thanks in advance!

Input array is longer than the number of columns

In the event dragdrop of a datagridview I got this error:
Here's the whole code of my dragdrop event :
Private Sub DataGridView1_DragDrop(sender As Object, e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragDrop
Dim clientPoint As Point = DataGridView1.PointToClient(New Point(e.X, e.Y))
Dim hit As DataGridView.HitTestInfo = DataGridView1.HitTest(clientPoint.X, clientPoint.Y)
Dim dgvr As DataGridViewRow = DirectCast(e.Data.GetData(GetType(DataGridViewRow)), DataGridViewRow)
Dim celldata As Object() = New Object(dgvr.Cells.Count) {}
For col As Integer = 0 To dgvr.Cells.Count - 1
celldata(col) = dgvr.Cells(col).Value
Next
Dim dt As New DataTable()
dt = ds_data.Tables(0)
Dim colCheckbox As DataColumn = dt.Columns.Add("Column1", GetType(Boolean))
Dim row As DataRow = dt.NewRow()
row.ItemArray = celldata
dt.Rows.InsertAt(row, hit.RowIndex)
dgvr.DataGridView.Rows.Remove(dgvr)
Dim sqlCmd As SqlCommand
sqlCmd = con.CreateCommand()
sqlCmd.CommandText = "update megatom_data_commande set ordre='" & hit.RowIndex & "' where id='" & DataGridView1.Rows(hit.RowIndex).Cells("ID").Value.ToString & "'"
Try
sqlCmd.ExecuteNonQuery()
DataGridView2.DataSource = ds_data2.Tables(0).DefaultView
DataGridView1.DataSource = ds_data.Tables(0).DefaultView
Dim CMD As New SqlCommand("PLANNIFIER")
CMD.Parameters.Add("#CHAINE", SqlDbType.VarChar).Value = cboChaine.SelectedItem.ToString
ExecuteCMD(CMD)
Catch ex As SqlException
End Try
End Sub
In fact my datatable have 15 columns but I added manually a checkbox column to select rows so I think i have a problem of indexes but I dont know how to resolve that problem.
My ds_data is defined like the code below:
requestPlanifie = "select megatom_data_commande.id as ID,numéro,observation,moule,commande,id_etat,programme,ordre,moule,glav,Qté_commandée_Totale," _
& " Qté_coupée_cuir, Qté_coupée_synthétique, Qté_piquée, Qté_finie from megatom_data_commande" _
& " inner join dbo.MEGATOM_DATA_MOULE on megatom_data_moule.id=megatom_data_commande.id_moule " _
& " where id_chaine='" & cboChaine.Text & "' and ( id_etat='3' or id_etat='4') order by numéro asc,ordre asc"
Dim dataAdapter As New SqlDataAdapter(requestPlanifie, con)
Try
dataAdapter.Fill(ds_data, "ds_data")
dataAdapter2.Fill(ds_data2, "ds_data2")
Catch ex As SqlException
End Try
DataGridView1.DataSource = ds_data.Tables(0).DefaultView