i am using vb.net and mysqladmin as my database.
i have a problem in my codes, and i don't know how to debug it.
please help me..
my problem is when i click the button update the error shows
"The CommandText property has not been properly initialized."
this is the codes:
Dim intDB_ID_Selected As Integer
'Private Sub cmdupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdupdate.Click
If MessageBox.Show("Do you want to update this record?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = vbYes Then
Dim sqlcommand As New MySqlCommand("UPDATE user_info " & _
" SET name = '" & txtname.Text.Trim & "'," & _
" address = '" & txtaddress.Text.Trim & "', " & _
" age = '" & txtage.Text.Trim & "', " & _
" WHERE id= '" & intDB_ID_Selected & "'", sConnection)
Call execCmd(SQL)
load1()
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
End If
End Sub `
Public Sub execCmd(ByVal PstrSQL As String)
With cmd
.CommandText = PstrSQL
.ExecuteNonQuery()
End With
End Sub
the error line is in
.ExecuteNonQuery()
i am a beginner in this language, so please help me. im begging you guys!!
what is cmd and has it been initialized?
Oh, and try to used parameterized query. The earlier you get into the habit, the better.
Try doing this instead after the messagebox selection. cmd is not properly initialized in execCmd.
Dim sqlStr as String = "UPDATE user_info " & _
" SET name = '" & txtname.Text.Trim & "'," & _
" address = '" & txtaddress.Text.Trim & "', " & _
" age = '" & txtage.Text.Trim & "', " & _
" WHERE id= '" & intDB_ID_Selected & "'", sConnection)
Dim sqlcommand As New MySqlCommand(sqlStr)
sqlcommand.ExecuteNonQuery()
load1()
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
Related
I am learning linq to dataset from this post: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/creating-a-dataview-object-linq-to-dataset
and I am having trouble when running this code, I do not understand why it doesn't work, however
The code works fine if I delete this line:
Where order1.Field(Of Integer)("Column2") = 1
my table have 4 columns corresponds to the name: Column1,2,3,4
Here is vbcode:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet = New System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source='C:\Users\Username\Downloads\Danh STT.xlsx';Extended Properties='Excel 12.0 Xml;HDR=YES;'")
MyCommand = New System.Data.OleDb.OleDbDataAdapter _
("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Author", "TestTable")
MyCommand.Fill(DtSet)
Dim orders As DataTable = DtSet.Tables(0)
Dim query = From order1 In orders.AsEnumerable
Order By order1.Field(Of String)("Column1")
Where order1.Field(Of Integer)("Column2") = 1
Select order1
Dim view As System.Data.DataView = New Data.DataView
view = query.AsDataView()
DataGridView1.DataSource = view
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Can you explain for me please!
Thanks a lot.
Edit: [The error I received]
{System.InvalidCastException: Specified cast is not valid." & vbCrLf & " at System.Data.DataRowExtensions.UnboxT1.ValueField(Object value)" & vbCrLf & " at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)" & vbCrLf & " at Dataview.Form1._Closure$__._Lambda$__1-0(DataRow order1) in D:\2.0_VSTO_PROJECT\D_1_MY_PROJECT\1 EXCEL\.NET\1 Class .Net\LinqExample\Dataview\Dataview\Form1.vb:line 31" & vbCrLf & " at System.Data.EnumerableRowCollection1.b__16_0(DataRow row)" & vbCrLf & " at System.Data.EnumerableRowCollection1.<>c__DisplayClass16_0.<GetLinqDataView>b__3(DataRow row)" & vbCrLf & " at System.Data.DataView.RowPredicateFilter.System.Data.IFilter.Invoke(DataRow row, DataRowVersion version)" & vbCrLf & " at System.Data.Index.AcceptRecord(Int32 record, IFilter filter)" & vbCrLf & " at System.Data.Index.InitRecords(IFilter filter)" & vbCrLf & " at System.Data.Index..ctor(DataTable table, IndexField[] indexFields, Comparison1 comparison, DataViewRowState recordStates, IFilter rowFilter)" & vbCrLf & " at System.Data.DataView.UpdateIndex(Boolean force, Boolean fireEvent)" & vbCrLf & " at System.Data.DataView.UpdateIndex(Boolean force)" & vbCrLf & " at System.Data.DataView.SetIndex2(String newSort, DataViewRowState newRowStates, IFilter newRowFilter, Boolean fireEvent)" & vbCrLf & " at System.Data.DataView..ctor(DataTable table, Predicate1 predicate, Comparison1 comparison, DataViewRowState RowState)" & vbCrLf & " at System.Data.EnumerableRowCollection1.GetLinqDataView()" & vbCrLf & " at System.Data.DataTableExtensions.AsDataView[T](EnumerableRowCollection1 source)" & vbCrLf & " at Dataview.Form1.Button1_Click(Object sender, EventArgs e) in D:\2.0_VSTO_PROJECT\D_1_MY_PROJECT\1 EXCEL.NET\1 Class .Net\LinqExample\Dataview\Dataview\Form1.vb:line 36}
I made several research but cannot figure out the problem. I can add, remove or edit rows from database in the code. However, I could not refresh the grid.
I mean, when I add new row to gridview, it doesn't appear in it. After I recompile the code it appears. How can I refresh the gridview?
Dim strSQL = "SELECT * FROM FIXEDCARD WHERE STKCODE = '" & TextEdit1.Text & "'"
objCon.Close()
Dim sqlCmd As New SqlCommand(strSQL, objCon)
objCon.Open()
Dim dreader As SqlDataReader
dreader = sqlCmd.ExecuteReader
If dreader.Read Then
'Dim stk_ As String = dreader.GetString(dreader.GetOrdinal("STKCODE")).ToString()
DevExpress.XtraEditors.XtraMessageBox.Show("already exists", "Info!", MessageBoxButtons.OK)
objCon.Close()
Else
dreader.Close()
strSQL = "INSERT INTO FIXEDCARD(STKCODE, STKEXP, AUTHCODE, GRPCODE, SPECODE" & _
", SPECODE2, SPECODE3, SPECODE4, SPECODE5, AMORTRATIO, AMORT," & _
"PURCH, SALES, RETUR, UNIT) VALUES('" & TextEdit1.Text & "'," & _
"'" & TextEdit2.Text & "', '" & TextEdit3.Text & "'," & _
"'" & TextEdit4.Text & "', '" & TextEdit5.Text & "'," & _
"'" & TextEdit6.Text & "', '" & TextEdit7.Text & "'," & _
"'" & TextEdit8.Text & "', '" & TextEdit9.Text & "'," & _
"'" & TextEdit10.Text & "', '" & TextEdit11.Text & "'," & _
"'" & TextEdit12.Text & "', '" & TextEdit13.Text & "'," & _
"'" & TextEdit14.Text & "', '" & TextEdit15.Text & "') "
sqlCmd = New SqlCommand(strSQL, objCon)
sqlCmd.ExecuteNonQuery()
objCon.Close()
End If
RefreshGrid()
Me.Close()
And also I try to write a refresh function that will refresh the gridview when I call it each button. However, I have been making a mistake but could not recognize it.
Public Sub RefreshGrid()
Dim T As New DataTable
Dim strSQL = "Select * From FIXEDCARD"
Dim sqlCmd As New SqlCommand(strSQL, objCon)
T = CType(sqlCmd.ExecuteNonQuery(), System.Data.DataTable)
GridView1.DataSource = T
End Sub
Public Function FillDataSet(query As String, ByVal ParamArray para() As Object) As DataTable
dim _transaction As SqlTransaction
Dim _command As SqlCommand
_command = New SqlCommand(query, yourConnection)
_ds = New DataSet
_sqlda = New SqlDataAdapter(_command )
_command.Transaction = _transaction
For i = 0 To para.Count - 1
_command.Parameters.AddWithValue("#" & i, para(i))
Next
_sqlda.Fill(_ds)
return _ds.tables(0)
End Function
call it
GridControl1.datasource = Nothing
GridControl1.datasource = FillDataSet(YourInsertQuery,YourParam)
GridControl1.RefreshDataSource()
You are using a "Non-Query" in the refresh. This doesn't return a table value.
Try using the SqlCommand.ExecuteReader method.
Reference: https://msdn.microsoft.com/en-us/library/9kcbe65k(v=vs.110).aspx
pls help solve me this question.. im very new to this
i can't add new employee to the table employee.. whenever i try to add it shows syntax error insert into statement
Public Class AddNewEmployee
Dim dr As OleDbDataReader
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim conn As New OleDbConnection(My.Settings.rayshadatabaseConnectionString)
Dim cmd As OleDbCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
conn.Open()
Try
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
cmd = New OleDbCommand(str, conn)
Dim i As Integer = cmd.ExecuteNonQuery()
If i > 0 Then
MessageBox.Show("Record Succesfully added.", "Process Completed", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Adding failed!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conn.Close()
cmd.Dispose()
End Try
frmEmployee.loadR()
Me.Close()
End Sub
End Class
Replace this,
Dim str As String = "INSERT INTO employee" _
& "(Employee Name, IC Number, HP Number, Address)" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
with this,
Dim str As String = "INSERT INTO employee" _
& "([Employee Name], [IC Number], [HP Number], [Address])" _
& " Values (" _
& "'" & txtEmployeeName.Text & "', " _
& "'" & txtIC_Number.Text & "'," _
& "'" & txtHP_Number.Text & "'," _
& "'" & txtAddress.Text & "')"
Thanks
Manoj
I'm running Visual studio and whenever I run my application it says "Incorrect syntax error near '(the email i enter appears here)'". I hope you can spot the mistake.
Within SQL server, my email column is called 'email'
Within Visual studio, the name of the input field for my email is called 'textEmail'
Public Sub AddCustomer(Firstname As String, Surname As String, Contactnum As String, Email As String)
Try
Dim strInsert As String = "INSERT INTO customers (firstname, surname, contactnum, email) " & _
"VALUES (" & _
"'" & Firstname & "'," & _
"'" & Surname & "'," & _
"'" & Contactnum & "'," & _
"'" & Email & "'"
MsgBox(strInsert)
SQLCon.Open()
SQLcmd = New SqlCommand(strInsert, SQLCon)
SQLcmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Code within form:
Private Sub cmdSave_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
'QUERY FOR CUSTOMER
SQL.RunQuery("SELECT * FROM customers WHERE customers.email = '" & txtEmail.Text & "' ")
If SQL.SQLDS.Tables(0).Rows.Count > 0 Then
MsgBox("This Email alredy exists!")
Exit Sub
Else
CreateCustomer()
End If
End Sub
Public Sub CreateCustomer()
' ADD CUSTOMER TO DATABASE
SQL.AddCustomer(txtFirst.Text, txtSur.Text, txtNum.Text, txtEmail.Text)
End Sub
End Class
Thanks for your time.
You are missing closing bracket
Dim strInsert As String = "INSERT INTO customers (firstname, surname, contactnum, email) " & _
"VALUES (" & _
"'" & Firstname & "'," & _
"'" & Surname & "'," & _
"'" & Contactnum & "'," & _
"'" & Email & "')"
When I try to edit and update the data in datagriview it comes up with an error message saying Operator '&' is not defined for type 'TextBox' and string "".
please help. Thanks
Here is my code
Private Sub btnaddrecord_Click(sender As Object, e As EventArgs) Handles btnaddrecord.Click
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
If Me.IdentificationNotest.Tag & "" = "" Then
cmd.CommandText = "INSERT INTO vehicledefects(Codenumber, vehiclereg, datereported, defects1, repaired1, defects2, repaired2, defects3, repaired3, datefixed) " & _
" VALUES(" & Me.IdentificationNotest.Text & ",'" & Me.vehiclereg.Text & "','" & Me.datereported.Text & "','" & Me.defects1.Text & "','" & Me.repaired1.Text & "','" & _
Me.defects2.Text & "','" & Me.repaired2.Text & "','" & _
Me.defects3.Text & "','" & Me.repaired3.Text & "','" & _
Me.datefixed.Text & "')"
cmd.ExecuteNonQuery()
Else
cmd.CommandText = "UPDATE vehicledefects" & _
" SET Codenumber =" & Me.IdentificationNotest.Text & _
", vehiclereg ='" & Me.vehiclereg.Text & "'" & _
", datereported ='" & Me.datereported.Text & "'" & _
", defects1 ='" & Me.defects1.Text & "'" & _
", repaired1 ='" & Me.repaired1.Text & "'" & _
", defects2 ='" & Me.defects2.Text & "'" & _
", repaired2='" & Me.repaired2.Text & "'" & _
", defects3='" & Me.defects3.Text & "'" & _
", repaired3='" & Me.repaired3.Text & "'" & _
", datefixed='" & Me.datefixed.Text & "'" & _
" WHERE Codenumber =" & Me.IdentificationNotest.Tag
cmd.ExecuteNonQuery()
End If
refreshdata()
Me.btnclear.PerformClick()
cnn.Close()
datefixed.Text = ""
IdentificationNotest.Text = ""
End Sub
In the future, you should also post the line number the error is being thrown on.
The error is telling you that you're doing something like:
dim myString as String = myTextBox & " some more text"
in this case, you would need to do:
dim myString as String = myTextBox.Text & " some more text"
In the code you posted, I wasn't able to find an instance of this - so perhaps its somewhere else in the code. Though, the code was hard to read so I may have missed it.
You may also be aware that this code is susceptible to SQL Injection attacks