Visual Basic 2015 (Visual Studio) - vb.net

I'm trying to create a Login Form using Visual Basic 2015 in Visual Studio. I've followed the instructions from a video that I've watched, however, an error occurred when I tried to run the code.
Here's the codes I've done so far:
Private Sub picgo1_Click(sender As Object, e As EventArgs) Handles picgo1.Click
openConn()
Dim dr As SqlDataReader
Dim cmd As SqlCommand
Dim sqlsyntax As String
cmd = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.Connection = conn
sqlsyntax = "select * from tblusers where user = '" & txtuser.Text & "' and pass = '" & txtpass.Text & "'"
cmd.CommandText = sqlsyntax
dr = cmd.ExecuteReader()
If dr.HasRows Then
MsgBox("Access Granted! Welcome '" & txtuser.Text & "'")
Else
MsgBox("Access Denied! Incorrect Username or Password!")
End If
conn.Close()
cmd.Dispose()
End Sub
Another for Module
Imports System.Data.SqlClient
Module ModuleConnections
Public conn As SqlConnection
Sub openConn()
Try
conn = New SqlConnection("Data Source=E:\HRIMS\HRIMS V1.0\WINDOWSAPPLICATION2\HRIMSDB.MDF;Integrated security=True")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Catch ex As Exception
MsgBox("Connecting to Database Failed" & ex.ToString)
End Try
End Sub
End Module
When I tried to run the form, here is the error I'm getting. Then when I pressed ok, it points me to this line.
I'm still trying to learn, so please don't be too hard on me :D
Thank you in advance.

Try:
Public conn As SqlConnection
Public Sub openConn()
conn = New SqlConnection(CONNECTIONSTRING)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Return conn
End Function
Login code:
Using cmd As New SqlCommand("SELECT *
FROM tblusers
WHERE user = #userName
AND pass = #userPass", openConn)
'Parameterize your query to be safe from SQL Injection
cmd.Parameters.AddWithValue("#userName", txtuser.Text)
cmd.Parameters.AddWithValue("#userPass", txtpass.Text)
Using rdr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleResult)
Dim Login As Object = 0
If rdr.HasRows Then
rdr.Read
Login = rdr(Login)
End If
If Login = Nothing Then
MsgBox("Access Denied! Incorrect Username or Password!")
Else
'MsgBox("Access Granted! Welcome '" & txtuser.Text & "'")
MsgBox(String.Format("Access Granted! Welcome {0}!", txtuser.text)
End If
End Using
End Using

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

VB.net 2010 dataset updates but access database remains same

I have tried to insert or update from my vb.net form into MS-Access database.
The dataset updates but the access database wont. Below is my code.
Try
Dim addLocation As String = "Insert into Provider (StateCode, Provider)" _
& "values ('" & ComboBox1.Text & "', '" & TextBox2.Text & "')"
Dim sqlcommand As New OleDbCommand
conn.Open()
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("One record added", MsgBoxStyle.Information)
refreshGrid()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Private Sub refreshGrid()
cnString = "PROVIDER = Microsoft.ace.oledb.12.0;data source =" & Application.StartupPath & "\HCHPClosedIn.accdb"
sqlQRY = "SELECT * FROM Provider"
conn = New OleDbConnection(cnString)
Try
conn.Open()
da = New OleDbDataAdapter(sqlQRY, conn)
Dim cb As OleDbCommandBuilder = New OleDbCommandBuilder(da)
da.Fill(ds, "Customers")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "Customers"
End Try
End Sub
Its been a while but I think I recall Access is kinda picky with commit. Try this:
With sqlcommand
.CommandText = addLocation
.Connection = conn
.ExecuteNonQuery()
.transaction = trans
End With
Trans.Commit()

how to simplify codes

I have a next button.
theres no error i just want to simplify
Try
lblcat.Text = ds.Tables("evaluation").Rows(cat)("QuestionCategory")
txt1.Text = ds.Tables("evaluation").Rows(CurrentRow)("Question")
txt2.Text = ds.Tables("evaluation").Rows(CurrentRow + 1)("Question")
txt3.Text = ds.Tables("evaluation").Rows(CurrentRow + 2)("Question")
txt4.Text = ds.Tables("evaluation").Rows(CurrentRow + 3)("Question")
txt5.Text = ds.Tables("evaluation").Rows(CurrentRow + 4)("Question")
Catch ex As Exception
End Try
every click to the next button my category and questions change.
every click i want also to save in my database
Private Sub Save_commit()
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
'get connection string declared in the Module1.vb and assing it to conn variable
con = New OleDbConnection(Get_Constring)
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
'I just use the textbox tag property to idetify if the data is new or existing.
sSQL = "INSERT INTO evaluationresult ([Com])" & _
" VALUES (?)"
cmd.CommandText = sSQL
cmd.Parameters.AddWithValue("#FacultyID", txtresult.Text)
'cmd.Parameters.AddWithValue("#IDNumber", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Com", OleDbType.Numeric).Value
' cmd.Parameters.AddWithValue("#Know", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Teaching", OleDbType.Numeric).Value
'cmd.Parameters.Addwithvallue("#man", OleDbType.Numeric).Value()
'cmd.Parameters.AddWithValue("#ID", OleDbType.Numeric).Value
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ErrorToString)
Finally
con.Close()
End Try
End Sub
please improve

vb login session

Hi I'm completely lost on this piece of code (also very new) I am trying to create a session after the else statement. How do you create a session and for it to be read by another file ?
Dim conn As MySqlConnection
'connect to DB
conn = New MySqlConnection()
conn.ConnectionString = "server=localhost;Port=3306; user id=****; password=****; database=testtable"
'see if connection failed.
Try
conn.Open()
Catch myerror As MySqlException
MessageBox.Show("Error Connection to Database: " & myerror.Message)
End Try
'sql query
Dim myAdapter As New MySqlDataAdapter
Dim sqlquery = "SELECT * FROM members Where login='" & UsernameTextBox.Text & "' and passwd='" & PasswordTextBox.Text & "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
'see if user exits.
If myData.HasRows = 0 Then
MessageBox.Show("Invalid Username/Password", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
Dim login As String = System.Web.HttpContext.Current.Session("login")
System.Web.HttpContext.Current.Session("login") = UsernameTextBox.Text
Dim Form1 = New Form1
Form1.Show()
Me.Visible = False
End If
Thanks for any help
Session only exists in ASP.Net.
You should pass information in constructor parameters and/or properties of your form classes.

Parameter with odbc error

i have a problem with supply parameter to store procedure with odbc, this is my procedure in module form Public cmd As OdbcCommand
Private Sub cmdapprove_Click(sender As Object, e As EventArgs) Handles cmdapprove.Click
cmd = New OdbcCommand("select * from mk_cuti where mk_nik='" & txtnik.Text & "'", conn)
rd = cmd.ExecuteReader
rd.Read()
rd.Close()
Call opendb()
If txtstatus.Text = 1 Then
Using (conn)
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_update_data_trans_cuti_terbawa"
cmd.Parameters.AddWithValue("#mk_nik", Me.txtnik.Text)
cmd.ExecuteNonQuery()
End Using
Dim updatestatus_hrd As String = "Update input_cuti set status_hrd=1 " & _
"where no_input='" & txtnoinput.Text & "'"
cmd = New OdbcCommand(updatestatus_hrd, conn)
cmd.ExecuteNonQuery()
Call datacutikaryawan()
Else
Dim updatestatus_hrd As String = "Update input_cuti set status_hrd=1 " & _
"where no_input='" & txtnoinput.Text & "'"
cmd = New OdbcCommand(updatestatus_hrd, conn)
cmd.ExecuteNonQuery()
Call datacutikaryawan()
End If
End Sub
when i run this procedure, i got massage this
ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Procedure
or function 'sp_update_data_trans_cuti_terbawa' expects parameter
'#mk_nik', which was not supplied.
I think anyone can help me? please
Here's one with your class:
Dim conn As New OdbcConnection(sConnString)
conn.Open()
Dim sqlCommand As String = "sp_update_data_trans_cuti_terbawa #mk_nik='" & Me.txtnik.Text & "'"
Dim command As New OdbcCommand(sqlCommand)
command.CommandType = CommandType.StoredProcedure
command.Connection = conn
command.ExecuteNonQuery()
Aight, I'm off to the nearest pub.
conn.execute("sp_update_data_trans_cuti_terbawa #mk_nik='" & Me.txtnik.Text & "'")
I have module with this
Imports System.Data.Odbc
Imports System.Data
Module koneksi
Public conn As OdbcConnection
Public str As String
Public da As OdbcDataAdapter
Public ds As DataSet
Public cmd As OdbcCommand
Public rd As OdbcDataReader
Sub opendb()
str = "Dsn=pmscuti;database=att2000;server=pams-01;uid=sa;pwd=pams123"
conn = New OdbcConnection(str)
If conn.State = ConnectionState.Closed Then
Try
conn.Open()
'MsgBox("Connection Successfully")
Catch ex As Exception
MsgBox(ex.Message)
Application.Exit()
End Try
End If
End Sub
End Module
can i know where the problem?