Visual Basic.Net 2010 Exception Error meaning - vb.net

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)

Related

Application with two forms is not showing

I am creating a form application using Visual Studio Express VB 2008 and SQL server 2008. I have two forms. When the program start is not showing me any form. What is to be done that I could use two forms as one program. For example, in one form I want to insert data type state, city .. and the other to use the same information for something else. But like I said, my first step is to see both forms in one program. What should I do to make it work
Imports System.Data.Sql
Imports System.Data.SqlClient
' This is my main form called form1 and through it I want to call a form called Country. Belonging to the same project. How to call a form ,,country,, that I could use
Public Class Form1
Dim objDS As New DataSet
Dim objDA As New SqlDataAdapter
Public Sqlcon As New SqlConnection With {.connectionString = "server=XXX\MSSQL2008;database=TEST;Trusted_Connection=True;"}
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If hasConnection() = True Then
MessageBox.Show("uspijesno povezano sa bazom")
End If
getSelc()
End Sub
Public Function hasConnection() As Boolean
Try
Sqlcon.Open()
Sqlcon.Close()
Return True
Catch ex As Exception
MessageBox.Show("Niste povezani sa bazom")
Return False
End Try
End Function
Public Function selc()
Dim objDS = New DataSet
Dim objDA As New SqlDataAdapter
Sqlcon.Close()
Sqlcon.Open()
Dim exCommand As String = ""
Dim myCommand As New SqlCommand
Dim commitTransaction = Sqlcon.BeginTransaction
Try
myCommand = New SqlCommand("EXECUTE " & "regionSelect" & " '" & txtID.EditValue & "', '" & txtShortN.EditValue & "', N'" & txtRegion.EditValue & "', '" & txtStatus.EditValue & "'", Sqlcon)
myCommand.Transaction = commitTransaction
objDA.SelectCommand = myCommand
objDA.Fill(objDS)
commitTransaction.Commit()
Sqlcon.Close()
MessageBox.Show("Podaci su uspijesno poslati")
Catch ex As Exception
MessageBox.Show(ex.Message)
commitTransaction.Rollback()
End Try
End Function
Private Sub SimpleButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
'insert()
End Sub
Private Sub btnConfirm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
getSelc()
End Sub
Public Function getSelc()
objDS = New DataSet
Dim com As New SqlCommand
Sqlcon.Close()
Sqlcon.Open()
GridControl1.DataSource = Nothing
Try
com = New SqlCommand("EXECUTE rS '" & txtID.Text & " ' , ' " & txtRegion.Text & "' , '" & txtShortN.Text & "', ' " & txtStatus.Text & " ' ", Sqlcon)
'com = New SqlCommand("SELECT * FROM tblRegion", Sqlcon)
objDA.SelectCommand = com
objDA.Fill(objDS)
com.CommandType = CommandType.StoredProcedure
GridControl1.DataSource = objDS.Tables(0)
objDA.Dispose()
com.Dispose()
Sqlcon.Close()
MessageBox.Show("Im here")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
'GridControl1.DataSource = Nothing
'objDS.Tables(0).Rows.Clear()
End Function
Private Sub SimpleButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton4.Click
getSelc()
Dim newRow As DataRow
newRow = objDS.Tables(0).NewRow
newRow.Item(0) = txtID.EditValue
newRow.Item(1) = txtShortN.EditValue
newRow.Item(2) = txtRegion.EditValue
newRow.Item(3) = txtStatus.EditValue
objDS.Tables(0).Rows.Add(newRow)
End Sub
Private Sub SimpleButton3_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton3.Click
End Sub
Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click
Country.Show() ' => Is this a good way, and is there any better way and more efficient
End Sub
End Class
You cannot load more than one form on Application Startup. You have to load any one form first then show others from its Form_Load event.
Private Sub StartupForm_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim form2 As New Form2
form2.Show()
Dim form3 As New Form3
form3.Show()
End Sub
Or you can load forms manually on Button Click.
Set the Form1 as a StartupForm from the Project Property Window.
Now, Add a button in your first form button1 and write down some code to display another form.
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Dim form2 As New Form2
form2.Show()
End Sub
Another one is calling main method. For that you need to assign Main method in your Project Property Window
Module mainModule
Sub Main()
Dim form2 As New Form2
form2.Show()
Dim form3 As New Form3
form3.ShowDialog()
End Sub
End Module

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.

Vb.net 2010 connectivity with MS Access 2007

I am using a form having 10 text boxes,1 register button & 1 exit button. I have created the database in MS Access 2007 and saved the file in desktop. I have connected by "Add New Data Source". Provider & Path is:Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\sipl\Desktop\Cust_Dtl.mdb. But when I click register the following error is showing:
con.Open() - Doesn't have a valid file name.
Here is my code:
Public Class Form2
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\sipl\Desktop\Cust_Dtl.mdb" & System.IO.Directory.GetCurrentDirectory & "Cust_Dtl.mdb"
Dim insertcmd As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand
Dim con As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection
con.ConnectionString = constring
insertcmd.CommandType = CommandType.Text
insertcmd.CommandText = String.Format("INSERT INTO {0} VALUES ('{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}')", "Table1", TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, TextBox6.Text, TextBox7.Text, TextBox8.Text, TextBox9.Text, TextBox10.Text)
insertcmd.Connection = con
con.Open()
Try
insertcmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End Sub
End Class
Please help to fix this problem. Thanks.
You are calling the database string twice:
Dim constring As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\sipl\Desktop\Cust_Dtl.mdb" & System.IO.Directory.GetCurrentDirectory & "Cust_Dtl.mdb"
This gives the string "C:\Users\sipl\Desktop\Cust_Dtl.mdbC:\Users\sipl\Desktop\Cust_Dtl.mdb"
Remove either C:\Users\sipl\Desktop\Cust_Dtl.mdb"
or & System.IO.Directory.GetCurrentDirectory & "Cust_Dtl.mdb

SQL connection error showing INVALID OBJECT NAME

I have done follwing coding but it shows error
Invalid object name 'sanket'
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim str As String
Private Sub ConnectToSQL()
Try
con.ConnectionString = "Data Source=SA_N_KET-PC\SQLEXPRESS;Initial Catalog=repeat;Integrated Security=true;"
con.Open()
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
'DoNothing.
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'CryrptDataSet.sanket' table. You can move, or remove it, as needed.
Me.SanketTableAdapter.Fill(Me.CryrptDataSet.sanket)
ConnectToSQL()
End Sub
Public Sub exe()
str = "insert into sanket(n)values ('" & TextBox1.Text & "')"
da = New SqlDataAdapter(Str, con)
da.Fill(ds, "sanket")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
exe()
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.