affect the result of sql query to textbox - vb.net

am using sqlserver 2008 and vb.net
i tried to affect the result of sql query to my textboxs.
here the code that i have tried
Dim rd As SqlDataReader
Try
Cn.Open()
cmd = New SqlCommand("SELECT pk_veh, désignation, projet, version, [taille de lot] from [Cutting software].dbo.vehicule WHERE désignation = '" & Form1.ComboBox3.SelectedValue & "'", Cn)
rd = cmd.ExecuteReader
While rd.Read
imp.TextBox1.Text = rd.GetInt32("pk_veh")
imp.TextBox2.Text = rd.GetString("désignation")
imp.TextBox3.Text = rd.GetString("projet")
imp.TextBox4.Text = rd.GetString("version")
imp.TextBox5.Text = rd.GetInt32("[taille de lot]")
imp.Show()
End While
Cn.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
while i checked the type of my columns i always have this error
System.InvalidCastException: 'La conversion de la chaîne "pk_veh" en type 'Integer' n'est pas valide.'FormatException: Input string was not in a correct format.
here the type of my columns
pk_veh,[taille de lot] : int
désignation,projet,version : varchar[50]

here the solution
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim rd As SqlDataReader
Try
Cn.Open()
Dim cmd As New SqlCommand("SELECT isnull(pk_veh,0)pk_veh, isnull(designation,'')designation, isnull(projet,'')projet, isnull(version,'')version, isnull(taille_de_lot,0)taille_de_lot from [Cutting software].dbo.vehicule WHERE designation = '" & Form1.ComboBox3.SelectedValue & "'", Cn)
rd = cmd.ExecuteReader
While rd.Read
imp.TextBox1.Text = rd.GetInt32(0)
imp.TextBox2.Text = rd.GetString(1)
imp.TextBox3.Text = rd.GetString(2)
imp.TextBox4.Text = rd.GetString(3)
imp.TextBox5.Text = rd.GetInt32(4)
End While
Cn.Close()
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
imp.Show()
End Sub

Related

the connection string property has not been initialized. vb.net access. BELOW is the code

Try
If MsgBox("SAVE THIS ACADEMIC YEAR?", vbYesNo + vbQuestion, title) = vbYes Then
cn.Open()
cm = New OleDbCommand("update [tblay] set status = 'CLOSE'", cn)
cm.ExecuteNonQuery()
cn.Close()
cn.Open()
cm = New OleDbCommand("INSERT INTO [tblay] (aycode,year1,year2,division)values(#aycode,#year1,#year2,#division)", cn)
With cm
.Parameters.AddWithValue("aycode", txtAY.Text)
.Parameters.AddWithValue("year1", txtYear1.Text)
.Parameters.AddWithValue("year2", txtYear2.Text)
.Parameters.AddWithValue("division", cboDivision.Text)
.ExecuteNonQuery()
End With
cn.Close()
MsgBox("NEW ACADEMIC YEAR HAS BEEN SUCCESSFULLY SAVED!", vbInformation, title)
With frmAY
.LoadRecords()
End With
Clear()
End If
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
This is the code to load records:
Sub LoadRecords()
Try
DataGridView1.Rows.Clear()
Dim i As Integer
cn.Open()
cm = New OleDbCommand("select * from tblay", cn)
dr = cm.ExecuteReader
While dr.Read
i += 1
DataGridView1.Rows.Add(i, dr.Item("aycode").ToString, dr.Item("year1").ToString, dr.Item("year2").ToString, dr.Item("division").ToString, dr.Item("status").ToString)
End While
cn.Close()
Catch ex As Exception
cn.Close()
MsgBox(ex.Message, vbCritical, title)
End Try
End Sub
This might be more than you want so if so sorry.
SQLite Database (DB) CRUD function are very Boiler Plate Code. That Said I use the same process repetably.
By pacing the code in Using blocks NO need to close the DB and other functions.
I create a button for each function SAVE DELETE and UPDATE that call the function.
Here are the functions.
This code needs to be placed top level
Public connStr As String = "Data Source={0};Version=3;"
Public conn As SQLiteConnection
Here is the SAVE data NOTE the '{gv_dbName} is declared in a Module.
Private Sub InsertSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
Try
cmd.CommandText = "INSERT INTO LinkTable (ytChannelName,ytLinkAddress,ytLastVisit,ytSiteType) VALUES (#ytChannelName,#ytLinkAddress,#ytLastVisit,#ytSiteType)"
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Insert Failed")
End Try
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
Here is the DELETE.
Private Sub DeleteSiteData()
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As New SQLiteCommand
cmd.Connection = conn
cmd.CommandText = "DELETE FROM LinkTable WHERE LID =" & gvID
cmd.ExecuteNonQuery()
End Using
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub
And the UPDATE.
Public Sub UpdateSiteData()
dateToday = CDate(CDate(Date.Today).ToString("M-d-yyyy"))
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;"),
cmd As New SQLiteCommand("UPDATE LinkTable SET ytChannelName = #ytChannelName, ytLinkAddress = #ytLinkAddress ,ytLastVisit = #ytLastVisit,ytSiteType = #ytSiteType WHERE LID =" & gvID, conn)
conn.Open()
cmd.Parameters.Add("#ytChannelName", DbType.String).Value = tbSiteName.Text.Trim
cmd.Parameters.Add("#ytLinkAddress", DbType.String).Value = tbUrl.Text.Trim
cmd.Parameters.Add("#ytLastVisit", DbType.String).Value = dateToday.ToString("M-d-yyyy")
cmd.Parameters.Add("#ytSiteType", DbType.String).Value = strType.Trim
cmd.Parameters.Add("#LID", DbType.String).Value = gvID
cmd.ExecuteNonQuery()
End Using
gvTxType = ""
frmStart.Show()
Close()
End Sub

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

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

Am new to asp.net and vb.net.,now am trying to make a gridview of a database table

now am trying to make a gridview of a database table named UploadProject.while selecting row of gridview display image in seperate image field by using imageurl At the time of compiling of following code image not displayed.an error occured..."incorect syntax near '='".Any body please help me to solve this problem
Protected Sub OnSelectedIndexChanged(sender As Object, e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
lblimageid.Text = row.Cells(0).Text
lbltitle.Text = row.Cells(1).Text
get_Address()
get_Image()
End Sub
Public Sub get_Address()
Dim qry As String
Try
cn.Open()
qry = "select (title,imageurl) from [UploadProject] where [id] = '" & lblimageid.Text & "'"
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes2.ForeColor = Drawing.Color.Red
lblmes2.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub get_Image()
Dim qry As String
Try
cn.Open()
qry = "select title,imageurl from UploadProject where id = " & lblimageid.Text
cmnd = New SqlCommand(qry, cn)
sdr = cmnd.ExecuteReader
While (sdr.Read())
lbltitle.Text = sdr.GetValue(0).ToString
Image2.ImageUrl = sdr.GetValue(1).ToString
End While
cn.Close()
Catch ex As Exception
lblmes1.ForeColor = Drawing.Color.Red
lblmes1.Text = ex.Message
Finally
cn.Close()
End Try
End Sub
Public Sub getProjectDT()
Dim qry As String
Try
qry = "select id,title,date from UploadProject "
sda = New SqlDataAdapter(qry, cn)
ds = New DataSet
sda.Fill(ds, "UploadProject")
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
Catch ex As Exception
Finally
cn.Close()
End Try
End Sub

transaction in ms access and vb.net

I am trying the below code but not getting executed.
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Using con As New OleDbConnection(connectionString)
Dim tra As OleDbTransaction = Nothing
Try
con.Open()
cmd.Transaction = tra
tra = con.BeginTransaction
Dim sqlstr As String = "insert into category(cname,comment) values('" + txtcategory.Text + "','" + txtcomment.Text + "')"
cmd = New OleDb.OleDbCommand(sqlstr, con)
cmd.ExecuteNonQuery()
Dim sql As String = "UPDATE tblInvoices SET avail = 1 WHERE (cname = txtcategory.Text)"
cmd = New OleDb.OleDbCommand(sqlstr, con)
cmd.ExecuteNonQuery()
tra.Commit()
Catch ex As Exception
MsgBox(ex.Message)
Try : tra.Rollback() : Catch : End Try
End Try
End Using
End Sub
I don't understand the transactions.
The command need to know about the existence of a Transaction. But you assign the Transaction instance before the opening the connection and then ask the connection to start the transaction.
In this way the command has a null reference for the transaction and not the good instance created by the connection. Also, when you create again the command, there is no transaction associated with it.
Better use the OleDbCommand constructor that takes a Transaction as third parameter
Private Sub btnsave_Click(sender As Object, e As EventArgs) Handles btnsave.Click
Using con As New OleDbConnection(connectionString)
Dim tra As OleDbTransaction = Nothing
Try
con.Open()
tra = con.BeginTransaction
Dim sqlstr As String = "insert into category(cname,comment)" &
" values(#cat, #com)"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.Parameters.Add("#cat", OleDbType.VarWChar).Value = txtcategory.Text
cmd.Parameters.Add("#com", OleDbType.VarWChar).Value = txtcomment.Text
cmd.ExecuteNonQuery()
Dim sql As String = "UPDATE tblInvoices SET avail = 1 " &
"WHERE cname = #cat"
cmd = New OleDb.OleDbCommand(sqlstr, con, tra)
cmd.Parameters.Add("#car", OleDbType.VarWChar).Value = txtcategory.Text
cmd.ExecuteNonQuery()
tra.Commit()
Catch ex As Exception
MsgBox(ex.Message)
tra.Rollback()
End Try
End Using
End
I have also changed your code to use a more safe approach to your queries. Instead of using a string concatenation use ALWAYS a parameterized query. In this way you are safe from Sql Injection, you don't have problems with parsing texts and your queries are more readable.