The multi-part identifier “System.Data.DataRowView” could not be bound." SQL SERVER + VB.NET - sql

Hi I am making a small database using sql server as the back and vb as the front end, I have nearly made it work however I have stumbled across this error.
My code is provided below would really appreciate some help.
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim cmd As New SqlCommand
conn = New SqlConnection(connectionstring)
conn.Open()
cmd = New SqlCommand("select tarif from tarif_sewa where kode_tarif = " & ComboBox1.Text & "", conn)
TextBox2.Text = cmd.ExecuteScalar
conn.Close()
End Sub
End Class

The correct approach at your query should be
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Using conn = New SqlConnection(connectionstring)
Using cmd = New SqlCommand("select tarif from tarif_sewa where kode_tarif = #p1", conn)
conn.Open()
cmd.Parameters.AddWithValue("#p1", ComboBox1.Text)
Dim result = cmd.ExecuteScalar
If result IsNot Nothing Then
' A better conversion could be applied knowing the exact datatype of tarif '
TextBox2.Text = result.ToString
End If
End Using
End Using
End Sub
This will replace your string concatenation with a parameterized query and enclose your disposable object in a Using statement.
However I can't figure out how this error could be emitted by your code that (while it is not to be recommended as best practice) is not formally wrong

Related

change format date and can update in textbox with blank or zero in vb.net

I wanted to change the date format in the textbox to the format "dd-mmm-yy" but it did not work when in datagridview did not appear the date with the time and also I could not update in the textbox with blank and zero which caused the error "data type error". if I do not perform sql command for update in the "DATE" field then do not cause error. I use visual studio 2010
so the problem in the date column and if I update without a date column then it runs perfectly. Problem error : syntax error in update statement
thanks
jack
Dim Path As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim cn As String = "provider=Microsoft.Jet.OLEDB.4.0; data source=" & Path & "; Extended Properties=dBase IV"
Private connectionString As String
Private con As OleDbConnection
Private cmd As OleDbCommand
Private da As OleDbDataAdapter
Private sql As String
Public x As Integer
Public Sub dbConnection()
connectionString = CStr(cn)
con = New OleDbConnection(connectionString)
con.Open()
End Sub
Private Sub DataGridView1_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
x = DataGridView1.Rows.IndexOf(DataGridView1.CurrentRow)
txtCODE.Text = DataGridView1.Rows(x).Cells(0).Value.ToString()
DateTimePicker1.Value = DataGridView1.Rows(x).Cells(1).Value.ToString()
NumericUpDown1.Value = DataGridView1.Rows(x).Cells(2).Value.ToString()
End Sub
Private Sub FillDataGridView()
Try
Dim query = "select CODE,DTE,QTY FROM EXAMPLE"
Using con As OleDbConnection = New OleDbConnection(CStr(cn))
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using da As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
da.Fill(dt)
Me.DataGridView1.DataSource = dt
End Using
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Try
dbConnection()
x = DataGridView1.Rows.IndexOf(DataGridView1.CurrentRow)
'sql = "UPDATE EXAMPLE SET QTY=? WHERE CODE=?"
sql = "UPDATE EXAMPLE SET DTE=?,QTY=? WHERE CODE=?"
cmd = New OleDbCommand(sql, con)
cmd.Parameters.Add("DTE", OleDbType.Date)
cmd.Parameters.Add("QTY", OleDbType.Numeric)
cmd.Parameters.Add("CODE", OleDbType.VarChar)
cmd.Parameters("DTE").Value = DateTimePicker1.Value
cmd.Parameters("QTY").Value = NumericUpDown1.Value
cmd.Parameters("CODE").Value = txtCODE.Text
cmd.ExecuteNonQuery()
MessageBox.Show("Successfully Updated...", "Update")
con.Close()
FillDataGridView()
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
FillDataGridView()
End Sub
Your SQL line must be written like:
sql = "UPDATE EXAMPLE SET DATE=#d,QTY=#q WHERE CODE=#c"
You set the values of these #xxx by adding more code:
cmd.Parameters.AddWithValue("#d", dtpDATE.Value)
cmd.Parameters.AddWithValue("#q", nudQTY.Value)
cmd.Parameters.AddWithValue("#c", txtCODE.Text)
Change your date time TextBox to be a datetimepicker instead. Instead of using textboxes for numeric values, use a NumericUpDown instead.
You must call AddWithValue("#xxx"... in the same order as the #xxx appear in the SQL. Access ignores the names and looks at the order Parameters appear in the SQL so it is important to call AWV on the same order. One day when you upgrade o using a different database it will support the name part of the parameter so you can add your values in any order but right now on access, order is important
You must write your SQL like I've shown. Never, ever do what you were doing before. Never use string concatenation to build a user-supplied data value into an SQL statement. It makes your program trivial to hack into. This might not matter while you're writing a tiny app to index grandma's record collection but it must never be done on any system of importance such as one used by many people

Visual Basic.Net 2010 Exception Error meaning

Can anyone Help me to figure out whats the meaning of this error statement.I keep getting this error statement:-
index (zero based) must be greater than or equal to zero and less than the size of the argument list
Below is my coding
Imports System.Data.OleDb
Public Class form2
Dim Mycn As OleDbConnection
Dim Command As OleDbCommand
Dim icount As Integer
Dim SQLstr As String
Private Sub Button1_Click_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Mycn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\lenovo\Documents\Final year stuff\BookStoreDb.mdb;")
Mycn.Open()
SQLstr = String.Format("INSERT INTO login VALUES('{0}','{1}','{2}','{3}','{4}')", TextBox1.Text, TextBox2.Text)
Command = New OleDbCommand(SQLstr, Mycn)
icount = Command.ExecuteNonQuery
MessageBox.Show(icount)
Catch ex As Exception
MessageBox.Show(ex.Message & " - " & ex.Source)
Mycn.Close()
End Try
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
End Class
As Plutonix suggested, just specify the two fields.
You can combine that with the parameters so you are also safe from injection attacks.
Try the following:
SQLstr = String.Format("INSERT INTO Login (User, Password) VALUES ('{0}','{1}')", TextBox1.Text, TextBox2.Text)
Command = New OleDbCommand(SQLstr, Mycn)

VB2010 & MSACCESS | Object reference not set to an instance of an object

i'm making a login form and every time i try to login(whether with a correct or not user) it gives me the same error.
"Object reference not set to an instance of an object"
Here's the code:
Public Class login
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Fausto\Documents\GitHub\CRE\cre.accdb;")
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=#p_userid AND PASSWORD=#p_passw;"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
Dim da As New OleDb.OleDbDataAdapter
Private Sub login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'I figured how to make comments in VB! Yeey
'Temporarely redirecting to menuForm
With cmd
.Parameters.AddWithValue("p_userid", username.Text)
.Parameters.AddWithValue("p_passw", password.Text)
End With
Try
conn.Open()
Dim usr As String = cmd.ExecuteScalar.ToString
If Not (IsDBNull(usr)) AndAlso usr = username.Text Then
Me.DialogResult = Windows.Forms.DialogResult.OK
Else
Me.DialogResult = Windows.Forms.DialogResult.Cancel
End If
Catch ex As Exception
MsgBox("Could not connect to DB hahahaha" & Environment.NewLine & "Error message: " & ex.Message)
Me.DialogResult = Windows.Forms.DialogResult.Cancel
Finally
conn.Close()
Me.Close()
End Try
End Sub
Private Sub closeBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeBtn.Click
End
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
credits.Show()
End Sub
End Class
I'm using Visual Basic Express and Microsoft Access 2010,
Thanks :D
I saw several issues, but I think the one addressed in the question is here:
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Fausto\Documents\GitHub\CRE\cre.accdb;")
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=#p_userid AND PASSWORD=#p_passw;"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
The problem is that those variables are class-level, initialized prior to the class constructor, and the order in which the variables are initialized is not guaranteed. What is happening is that, at the point when the New OleDb.OleDbCommand(sql, conn) code executes, the conn variable is not guaranteed to have initialized.
This omission will fly under the radar, all the way until you try to execute a command, here:
Dim usr As String = cmd.ExecuteScalar.ToString
Aside from needing parentheses for the function call, it's not unil this point that the OleDbCommand object finally tries to use the connection supplied earlier and discovers that there's Nothing there.
While I have your attention, I also need to point out that you're using the wrong parameter notation for OleDb (you need to use ? placeholders instead of #NameParameters). Also, this is a horrible way to handle authentication. NEVER store a password in plain text like that.

Syntax error in INSERT into statement when adding to access database

Someone please help me on finding the error on my code.
the error is at the line inside my try and catch where im trying to add record on my database Access. the error is "Syntax error in INSERT into statement". I already tried using
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
on my registration for voters and it works fine. idk why it doesnt work on this form (user registration).
Imports System.Data.OleDb
Public Class UserRegister
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Label4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label4.Click
End Sub
Private Sub UserRegister_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = " PROVIDER=Microsoft.jet.OLEDB.4.0;"
dbSource = "Data Source= C:\Users\Ronel\Documents\database\CSdatabase.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT*FROM tblUsers"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Users")
MsgBox("Database now Open")
con.Close()
'MsgBox("Database now Close")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
Dim empty =
Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
MessageBox.Show(String.Format("PLEASE FILL ALL FIELDS:"))
Else
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("Username") = TextBoxUser.Text
dsNewRow.Item("Password") = TextBoxPass.Text
dsNewRow.Item("LastName") = TextBoxFN.Text
dsNewRow.Item("GivenName") = TextBoxGN.Text
dsNewRow.Item("MiddleName") = TextBoxMN.Text
' Try
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
' Catch ex As Exception
MsgBox("Error updating")
' End Try
' Me.Dispose()
'Comelec.Show()
End If
End Sub
End Class
I see a few problems. First, your SQL statement needs some spaces in it. Instead of sql = "SELECT*FROM tblUsers", use sql = "SELECT * FROM tblUsers".
Second, when using OleDbCommandBuilder, the code connects to the database using the SELECT statement you provided for the DataAdapter, and uses that to generate the necessary SQL for Update, Delete, and Insert statements. The connection to the database needs to be open for this to occur -- you connection is closed at the point where the CommandBuilder is running. This is probably where the syntax error is coming from.
The CommandBuilder will create these statements using all of the fields specified in the SELECT. If you have fields in your Users table other than the five you are attempting to populate, the OleDbCommandBuilder is still going to build an INSERT statement that will attempt to fill those fields as well. Depending on how your table is structured, this may cause rows to be rejected if required fields aren't populated. To take a look at what SQL statements are being generated, you can look at properties of the DataAdapter object after using the CommandBuilder:
con.Open
sql = "SELECT * FROM tblUsers"
da = New OleDb.OleDbDataAdapter(sql, con)
Dim cb As New OleDb.OleDbCommandBuilder(da)
Debug.Print("SELECT: " & da.SelectCommand.CommandText)
Debug.Print("UPDATE: " & da.UpdateCommand.CommandText)
Debug.Print("DELETE: " & da.DeleteCommand.CommandText)
Debug.Print("INSERT: " & da.InsertCommand.CommandText)
Some additional reading on CommandBuilders is available here: http://msdn.microsoft.com/en-us/library/tf579hcz%28v=vs.110%29.aspx
Give this a try:
Imports System.Data.OleDb
Public Class UserRegister
Const dbProvider As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource As String = "Data Source=C:\Users\Ronel\Documents\database\CSdatabase.mdb"
Dim con As New OleDb.OleDbConnection(dbProvider & dbSource)
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
'Specify only the fields you need
Dim sql As String = "SELECT UserName, Password, LastName, GivenName, MiddleName FROM tblUsers"
Private Sub UserRegister_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Users")
' Get commands now, while connection is open. Do this once when the form is loaded, not every time button is clicked.
Dim cb As New OleDb.OleDbCommandBuilder(da)
con.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Validation code goes here
If empty.Any Then
MessageBox.Show(String.Format("PLEASE FILL ALL FIELDS:"))
Else
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("Username") = TextBoxUser.Text
dsNewRow.Item("Password") = TextBoxPass.Text
dsNewRow.Item("LastName") = TextBoxFN.Text
dsNewRow.Item("GivenName") = TextBoxGN.Text
dsNewRow.Item("MiddleName") = TextBoxMN.Text
Try
con.Open()
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
Catch ex As Exception
MsgBox("Error updating: " & Err.Description)
Finally
con.Close()
End Try
End If
End Sub
End Class

I'm trying to create a login form in VB.NET. I'm having some difficulties running my form

I got the error "invalid cast exception unhandled." I'm using SQL Server 2008 and Visual Studio 2008. I get conversion from String "Jack" to type Boolean is not valid.
See the code of my form below:
Imports System.Boolean
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim username As String
Dim pswd As String
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim reader As SqlDataReader
username = txt_username.Text
pswd = txt_password.Text
txt_username.Text = Focus()
txt_password.Visible = "False"
Try
conn = New SqlConnection("data source=TAMIZHAN\SQLEXPRESS;persistsecurity info=False;initial catalog=log;User ID=sa;Password=123");
cmd = New SqlCommand("Select usename,passw from Userlog where usename='" + username + "' & passw='" + pswd + "'")
conn.Open()
reader = cmd.ExecuteReader()
If (String.Compare(pswd and '"+passw+"')) Then
MsgBox("Success")
End If
If (reader.Read()) Then
MsgBox("Login success")
End If
conn.Close()
Catch ex As Exception
MsgBox("Error"+ex.Message());
End Try
End Sub
End Class
The string.Compare returns an Integer not a boolean and should be called in this way
If (String.Compare(pswd,passw) = 0) Then
MsgBox("Success")
End If
Please see the references on MSDN
However your code has many problems as it stands now:
You are using string concatenation to build your sql text
(SqlInjection, Quoting problems).
You don't use the Using statement (connection remains open in case of
exception).
The compare logic seems to be absolutely not needed.