Problems passing values from one form to another - vb.net

I'm new to VB.net. So here is what I want to do which I am having some serious problem
Using the "Get_Computer_Name form" will post the username and account type into another form. The Get_Computer_Name also gets the computer name where it will be sent to a module and that module will work as the main connection. Now I have tried to separate the login form and form that gets the computer name but that didn't work (I also want to try that method).
The problem with my current method is that it can only perform one thing at a time. It fails to post the username and account type and it fails to send the computer name to the module. Now strangely there is a way around. If I comment out the post username and account type, the computer name will be sent to the module and the module will work and connect to the database. Now if I choose not to comment out the code that post the username and account to the other form, the computer name won't be sent to the module that handles the connection thus failing to connect to the database.
I am open to other suggestions rather than doing it this way.
Thank you
'Here is my code for "Get_Computer_Name form"
Imports System.Data.SqlClient
Public Class Get_Computer_Name
Public Sub Get_Computer_Name_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
cmbcomputername.Text = My.Computer.Name
connect()
End Sub
Private Sub cmbcomputername_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbcomputername.SelectedIndexChanged, cmbcomputername.TextChanged
cmbcomputername.Text = My.Computer.Name
End Sub
Public Sub btnlogin_Click(sender As System.Object, e As System.EventArgs) Handles btnlogin.Click
datasource = cmbcomputername.Text
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
Dim reader As SqlDataReader
Dim sqlstatement As SqlCommand = New SqlCommand
sqlstatement.Connection = connection
Try
sqlstatement.CommandText = "Select account_username, account_password, account_type " &
"from account_login where account_username='" & txtusername.Text & "' and account_password='" & txtpassword.Text & "'"
reader = sqlstatement.ExecuteReader()
If (reader.Read()) Then
Dim application_form As application_form
application_form = New application_form
application_form.Show()
application_form = Nothing
Me.Visible = False
'This is the code that post the username and account type to the other form (application form). If I comment this code out, the system successfully connects to the database
application_form.lblusername.Text = (reader("account_username").ToString)
application_form.lblaccount_type.Text = (reader("account_type").ToString)
sqlstatement.Dispose()
reader.Close()
connection.Close()
Else
connection.Close()
MsgBox("Invalid")
End If
reader.Close()
Catch ex As Exception
End Try
End Sub
End Class
'This is the code for the module that holds the main connection string
Public connection As SqlConnection = New SqlConnection
Public datasource As String
Public database As String = "bpmi"
Public sqlmainconnector As String
Public Sub connect()
sqlmainconnector = "Data Source=" & datasource & ";Initial Catalog=bpmi;Integrated Security=True"
connection.ConnectionString = sqlmainconnector
Try
If connection.State = ConnectionState.Closed Then
connection.Open()
Else
connection.Close()
End If
Catch ex As Exception
End Try
End Sub
'And this code is the form where the username and account type will be posted
Imports System.Data.SqlClient
Public Class application_form
Dim sqlcommand As SqlCommand
Dim da As SqlDataAdapter
Dim table As New DataTable
Dim dategrabberapp As String
Dim dategrabberben As String
Dim benidgrabber As String
Private Sub Form1_Load(sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
connect()
filldatagrid(updateappdatagrid, updatebendatagrid)
fillcomboboxstatus(cmbstatus)
fillcomboboxposition(cmbappworkposition)
fillcomboboxrelationship(cmbrelation)
fillcomboboxrelationshipupdate(cmbrelationbenupdate)
fillcomboboxstatusupdate(cmbappstatusupdate)
fillcomboboxpositionupdate(cmbappworkposupdate)
'this is where the account type will got to
If lblaccount_type.Text <> "Administrator" Then
Me.TabControl1.TabPages(1).Enabled = False
Me.TabControl1.TabPages(2).Enabled = False
MsgBox("As a 'Staff', you are not permitted to do any updates")
updateappdatagrid.Hide()
updatebendatagrid.Hide()
End If
End Sub
End Class

Related

System.InvalidOperationException ExecuteNonQuery requires an open and available Connection

The following code is supposed to display information from a database but there is an error (the title of this question) on the DBCmd.ExecuteNonQuery() line of code.
Does anyone know how I can resolve this problem?
• I am using VB.NET
• I am using an Access database
The code is:
Imports System.Data.OleDb
Public Class frmCheckAvailablity
Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=|DataDirectory|\NewHotel.mdb;")
Private Access As New DBControl
Dim QRY As String
Private DBCmd As OleDbCommand
Dim DBDR As OleDbDataReader
Public DBDA As New OleDbDataAdapter("SELECT RoomType FROM tblRoomBookings", DBCon)
Public DT As New DataTable
Public DS As New DataSet
Public DR As DataRow
Private Function NotEmpty(text As String) As Boolean
Return Not String.IsNullOrEmpty(text)
End Function
Private Sub frmCheckAvailability_Shown(sender As Object, e As EventArgs) Handles Me.Shown
'RUN QUERY
Access.ExecQuery("SELECT * FROM tblRoomBookings ORDER BY BookingID ASC")
If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
End Sub
Private Sub frmCheckAvailability_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'NewHotelDataSet.tblRoomBookings' table. You can move, or remove it, as needed.
Me.TblRoomBookingsTableAdapter.Fill(Me.NewHotelDataSet.tblRoomBookings)
If DBCon.State = ConnectionState.Closed Then DBCon.Open() : Exit Sub
End Sub
Private Sub Search()
DBDA.Fill(DT)
txtSearch.AutoCompleteCustomSource.Clear()
For Each DBDR In DT.Rows
txtSearch.AutoCompleteCustomSource.Add(DBDR.Item(0).ToString)
Next
txtSearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
End Sub
Private Sub SearchCustomers(RoomType As String)
'ADD PARAMETERS & RUN QUERY
Access.AddParam("#RoomType", "%" & RoomType & "%")
Access.ExecQuery("SELECT * FROM tblRoomBookings WHERE RoomType LIKE #RoomType")
'REPORT & ABORT ON ERRORS
If NotEmpty(Access.Exception) Then MsgBox(Access.Exception) : Exit Sub
End Sub
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
QRY = "SELECT FullName FROM tblRoomBookings WHERE RoomType'" & txtSearch.Text & "'"
DBCmd = New OleDbCommand(QRY, DBCon)
DBCmd.ExecuteNonQuery()
DBDR = DBCmd.ExecuteReader
If DBDR.Read Then
txtRoomType.Text = DBDR("RoomType")
txtFirstNight.Text = DBDR("FirstNight")
txtLastNight.Text = DBDR("LastNight")
txtNoNights.Text = DBDR("NoNights")
End If
End Sub
The only place in the code that I see DBcmd.ExecuteNonQuery is in search text changed event. Do really want to run this code every time the users types a letter?
Do not create a new connection at the class (Form) level. Every time the connection is used it needs to be disposed so it can be returned to the connection pool. Using...End Using blocks handle this for you even if there is an error.
Don't call .ExecuteNonQuery. This is not a non query; it begins with Select.
You can't execute a command without an Open connection.
Never concatenate strings for sql statments. Always use parameters.
The connection is open while the reader is active. Don't update the user interface while the connection is open.
Load a DataTable and return that to the user interface code where you update the user interface.
Private ConStr As String = "Your connection string"
Private Function GetSearchResults(Search As String) As DataTable
Dim dt As New DataTable
Dim QRY = "SELECT FullName FROM tblRoomBookings WHERE RoomType = #Search"
Using DBcon As New OleDbConnection(ConStr),
DBCmd As New OleDbCommand(QRY, DBcon)
DBCmd.Parameters.Add("#Search", OleDbType.VarChar).Value = Search
DBcon.Open()
Using reader = DBCmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub txtSearch_TextChanged(sender As Object, e As EventArgs) Handles txtSearch.TextChanged
Dim dtSearch = GetSearchResults(txtSearch.Text)
If dtSearch.Rows.Count > 0 Then
txtRoomType.Text = dtSearch(0)("RoomType").ToString
txtFirstNight.Text = dtSearch(0)("FirstNight").ToString
txtLastNight.Text = dtSearch(0)("LastNight").ToString
txtNoNights.Text = dtSearch(0)("NoNights").ToString
End If
End Sub

My Oledb DataAdapter.Fill code is "missing parameters"

I am trying to set-up a login page that checks the user's credentials from an MS Access database. When I run the code, it says that the fill method needs one or more parameters. Here's the code I'm using:
Public Class login
Public Shared dslogin As New DataSet
Public Shared con As New OleDb.OleDbConnection
Dim da1 As New OleDb.OleDbDataAdapter
'Global variables
Public Shared currentloginID As Integer = 0
Public Shared tbusername As TextBox
Public Shared tbpassword As TextBox
Private Function OpenDBConnection1()
Dim directory1 As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Return "PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = " & directory1 & "\IEshiDBv1.accdb"
End Function
'login button
Private Sub btnLOGIN_Click(sender As Object, e As EventArgs) Handles btnLOGIN.Click
Dim username As String = txtusername.Text
Dim password As String = txtpassword.Text
If username = "" Or password = "" Then
MsgBox("Please enter log-in details")
con.Close()
Exit Sub
Else
Dim sqllogin As String = ("SELECT * FROM LoginRcrds WHERE LoginUserName = " & username)
da1 = New OleDb.OleDbDataAdapter(sqllogin, con)
da1.Fill(dslogin, "LoginCredentials")
con.Close()
Dim dtlogin As DataTable = dslogin.Tables("LoginCredentials")
Dim rowlogin As DataRow
For Each rowlogin In dtlogin.Rows
If password = rowlogin("LoginPW") Then
homepage.Show()
Me.Hide()
Exit For
End If
Next
MsgBox("Incorrect log-in credentials. Please try again")
Exit Sub
End If
End Sub
'Onload subroutine
Private Sub login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = (OpenDBConnection1())
con.Open()
End Sub
End Class
The error occurs at
da1.Fill(dslogin, "LoginCredentials")
and the error message says " No value given for one or more required parameters."
I read somewhere that .Fill requires three parameters: (DataSet, RecordSet, TableName). I never tried this because I don't understand what RecordSet means.
Edit: I've checked another program with a 4.0 Oledb provider and changed it to 12.0. The same error appeared. It seems that the Fill method of the DataAdapter of Oledb 12.0 requires more than 2 parameters. Can somebody explain this?

An exception of type 'System.InvalidOperationException' occurred in System.Data.dll

This is my code. help me to solve it thanks!
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed
Imports System.Data.SqlClient
Partial Class Staff
Inherits System.Web.UI.Page
' Dim conn As New SqlConnection("Data Source=USER-PC\SQLEXPRESS;Initial Catalog=carrental;Integrated Security=True;Pooling=False")
Dim con As New Data.SqlClient.SqlConnection
Dim cmd As New Data.SqlClient.SqlCommand
Dim dr As Data.SqlClient.SqlDataReader
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
con.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user\Desktop\oh manisku\PROJECT ABIS\project baru\project baru\App_Data\order.mdf;Integrated Security=True;Connect Timeout=30")
con.Open()
Catch ex As Exception
' MsgBox(ex.Message)
End Try
End Sub
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
cmd.CommandText = ("Select Username, Password from Admin WHERE Username ='" & txtusername.Text & "' and Password = '" & txtPass.Text) & "' "
cmd.Connection = con
dr = cmd.ExecuteReader
con.Close()
If dr.HasRows Then
MsgBox("Succesfully Login")
Response.Redirect("recalled.aspx")
Else
MsgBox("Invalid Username and Password")
End If
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
End Sub
Protected Sub SqlDataSource1_Selecting(sender As Object, e As SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting
End Sub
End Class
As I said in my comment, you're closing the connection before reading the data. You should move the connection close to after you finished with the data reader.
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Dim con As New Data.SqlClient.SqlConnection
con.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user\Desktop\oh manisku\PROJECT ABIS\project baru\project baru\App_Data\order.mdf;Integrated Security=True;Connect Timeout=30")
con.Open()
cmd.CommandText = ("Select Username, Password from Admin WHERE Username ='" & txtusername.Text & "' and Password = '" & txtPass.Text) & "' "
cmd.Connection = con
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("Succesfully Login")
Response.Redirect("recalled.aspx")
Else
MsgBox("Invalid Username and Password")
End If
dr.Close() ' close the datareader
con.Close() ' close the connection
End Sub
Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
End Sub
Calling ExecuteReader simply opens the stream. If you close the connection, you close the stream. To use a telephone analogy: it's like hanging up on someone, and then trying to have a conversation.
Please also switch to using parameterized queries since, as it stands, I could enter my username as ' OR 1 = 1 ; -- and I'd gain full access to the first account in your system.
Also, please look into ways to securely store passwords. You should never store passwords in your database in plain text, and you should never store passwords in a way that allows you to reverse them to the original user input. Passwords should be hashed with a salt. see here.

user login in vb.net Windows Form

I'm sorry for disturbing you guys, but I had a question to ask. I'm currently doing a program where user which are in the access database can log in, the code is working but the problem is that when I debug I can only login using 1 user, when I try logging in using another user account it shows Login Invalid and I'm not sure why. I hope someone could pin point what am I doing wrong;
Here's my code;
Imports System.Data.OleDb 'provides classes to connect to the database
Imports System.Data
Imports System.IO
Public Class Login
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Function getcount() As Integer
Using conn As New OleDb.OleDbConnection _
("Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & Application.StartupPath & "\User.mdb")
'provider to be used when working with access database
conn.Open()
Dim cmd As New OleDb.OleDbCommand("Select COUNT(*) FROM UserProf_table", conn)
Return cmd.ExecuteScalar()
End Using
End Function
Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
conn = New OleDbConnection
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & Application.StartupPath & "\User.mdb"
conn.Open()
If getcount() = 1 Then
btnReg.Visible = False
Else
btnReg.Visible = True
End If
MsgBox(conn.State.ToString()) 'to check connection
End Sub
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim idbx As String ' noted that ID is numbers
Dim pwd As String
idbx = idbox.Text
pwd = pwdbox.Text
With cmd
'Open Connection for executereader
If Not conn.State = ConnectionState.Open Then
conn.Open()
End If
'initialized database connection
.Connection = conn
.CommandText = "SELECT UserID, UserPwd FROM UserProf_table WHERE UserID = '" & idbox.Text & "' AND UserPwd = '" & pwdbox.Text & "'"
Dim dr As OleDbDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
dr.Read()
If idbx = dr.Item("UserID") And pwd = dr.Item("UserPwd") Then
idbx = SystemInformation.UserName
mainForm.Show()
Me.Hide()
Else
MsgBox("Password or username is incorrect")
idbox.Clear()
pwdbox.Clear()
End If
dr.Close()
End If
End With
'close connection
conn.Close()
End Sub
Private Sub btnReg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReg.Click
registerForm.Show() ' Register form
Me.Hide()
End Sub
End Class
Here's my database:
I login using the UserID and UserPwd. And is there a way for me to save the UserID do that I can use it in different form? Thank you in advance
You are always reading the whole username/password list!
You have forgotten a WHERE clause in :
SELECT UserID, UserPwd FROM UserProf_table
WHERE UserId = ???
You can login as the first user because it's the first row returned!
[Also: please don't store passwords as plain text]
You should change your sql command to retrieve only 1 record:
.CommandText = "SELECT UserID,UserPwd FROM UserProf_table WHERE UserId =" + idbx.trim()
Moreover, if you are using Visual Studio, you can use "Watch and QuickWatch Windows" in debug mode to show your variables and make sure they return expected values.
https://msdn.microsoft.com/en-us/library/0taedcee.aspx

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.