Row data into string conversion vb.net 2010 - database

How can I convert a row data into string or text and display it into a label? My problem is when I click on my login button which contains the SQL code that gains a row data into alabel, the result in my label is false. not the text. How can I convert it into string?
Here's my code:
Private Sub cmdLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLog.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim adaptor As New SqlClient.SqlDataAdapter
Dim dataset As New DataSet
Dim reader As MySqlDataReader = Nothing
Dim sapi
sapi = CreateObject("sapi.spvoice")
connection.ConnectionString = ("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Calupad\Desktop\HTF feat Yiyet\HTF feat Yiyet\Database1.mdf;Integrated Security=True;User Instance=True")
command.CommandText = "SELECT * FROM [Users] WHERE Username='" & txtUser.Text & "' AND Password ='" & txtPass.Text & "';"
txtWel.Text = "Welcome Back, " + txtUser.Text + "!....."
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(dataset, "0")
txtStat.text = command.CommandText = "SELECT Status FROM [Users] WHERE Username = '" & txtUser.Text & "' ".ToString
txtStat.Text = stat
Dim count = dataset.Tables(0).Rows.Count
If count > 0 Then
MsgBox("Login Successful!" & vbNewLine & txtStat.Text, MsgBoxStyle.Information, "Access Granted")
sapi.speak(txtWel.Text)
Me.Hide()
Form1.Show()
frmMenu.Show()
txtUser.Clear()
txtPass.Clear()
tries = 3
Else
ctr = tries - 1
tries = ctr
sapi.speak(txtUser.Text + txtNot.Text)
MsgBox("Invalid Account!" + vbNewLine + "Attempts Remaining: " & tries, vbCritical, "Access Denied")
txtUser.Clear()
txtPass.Clear()
If tries = 0 Then
MsgBox("You've reached the maximum attempts!" + vbNewLine + "The program will be terminated.", vbCritical, "Terminated!")
Me.Close()
End If
End If
End Sub

First of all, the way you check for username and password is weak and is most certainly volnurable to SQL injections. You are checking if the 'count' of rows is greater than zero then the user has logged in successfully, where as you should only compare count to 1. and instead of counting the rows, try to compare the row values to what the user has input in the username and passoword fields and what is returned from the database rows.
The "hacker" can simply type this and he will be allowed to log in according to the logic of your code:
You just need to retrieve the data stored into dataset variable that you filled using the adapter.
Assuming your database table contains fields like First_Name and 'Last_Name', here is how you can display them on any label control on your form:
adaptor.Fill(dataset, "0")
myFirstName.Text = dataset.Tables(0).Rows(0).Item("First_Name").ToString()
myLastName.Text = dataset.Tables(0).Rows(0).Item("First_Name").ToString()
You can also retrieve the column without having to know its name like this
myLabel.text = = dataset.Tables(0).Rows(0).Item(3).ToString()
'This will retrieve the 4th column from the table (zero based array)
You can also clean up your code by declaring a variable to hold the retrieved table
adaptor.Fill(dataset, "0")
Dim myTable as DataTable = dataset.Tables(0)
myFirstName.Text = myTable.Rows(0).Item(0).ToString()
Hope this helps

Related

Saving all items from 2 listboxes to a SQL Server database

I am trying to take all the items from a list box and save them into separated fields into a SQL Server database. The user pushes a save button and I would like for all of the items in the list box to be separated into their appropriate fields and saved into said fields in the SQL Server database. The items start out separated in a DGVgrid and are combined when the enter the List box. What is the best way to go about this? The SQL Server database has the same columns and the DGVgrid.
I am using VB in Visual Studio and a SQL Server database that I have created on my machine. Any help would be greatly appreciated. I have been stuck on this for a bit and I'm not sure where to go from here.
I think that the problem may be the List boxes because I have been able to save to my SQL Server database when the data comes from Text boxes, but I do not want to get rid of the List boxes. I have tried changes the List boxes out with DGVgridview boxes, but this did not work. I could not get the items to neatly go into the columns that they needed to. Would I be better of just trying to save the data into a Text file?
Public Function InStrRev(StringCheck As String, StringMatch As String, Optional Start As Integer = -1, Optional Compare As CompareMethod = Microsoft.VisualBasic.CompareMethod.Binary) As Integer
End Function
Public Function InStr(Start As Integer, String1 As String, String2 As String, Optional Compare As CompareMethod = Microsoft.VisualBasic.CompareMethod.Binary) As Integer
End Function
Public Function Mid(Str As String, Start As Integer, Length As Integer) As String
End Function
Static IntStart As Integer
Dim Backpack1 = BP1ListBox.ToString()
Dim Backpack2 = BP2ListBox.ToString()
Dim user As String = ReturningUser.UserNametxt.Text
Dim con As SqlConnection
Dim deletecmd As SqlCommand
Dim objcmd As SqlCommand
Dim deletereader As SqlDataReader
Dim reader As SqlDataReader
Dim BackpackName As String
Dim item As String
Dim weightposition As Integer
Dim weight As String
Dim username As String = CStr(ReturningUser.UserNametxt.Text)
Dim delete As String = "Delete From UserBackpackItems where UserName = '" & username & "'"
Dim stmt As String = "Insert Into UserBackpackItems(UserName, BackpackName, Item, Weight,) Values('" & username & "', '" & BackpackName & "', '" & ItemNametxt.Text & "', '" & ItemWeighttxt.Text & "')"
con = New SqlConnection("Data Source=DESKTOP-AUS1VBC\SQLEXPRESS;Initial Catalog=BackpackDatabase;Integrated Security=True")
con.Open()
'delete previous save
deletecmd = New SqlCommand(delete, con)
deletereader = deletecmd.ExecuteReader()
'create a new save
For Counter = IntStart To BP1ListBox.Items.Count - 1
Dim ListItems As String = BP1ListBox.Items.ToString
item = Mid(ListItems(Counter), 1, InStr(1, ListItems(Counter), " ", CompareMethod.Text))
weightposition = InStrRev(ListItems(Counter), " ", CompareMethod.Text)
weight = Mid(ListItems(Counter), weightposition, Length:=BP1ListBox.Items(Counter))
objcmd = New System.Data.SqlClient.SqlCommand(stmt, con)
reader = objcmd.ExecuteReader()
Next

Login form by using a new database, made in VB

I'm a few day's searching for a problem, but can't find the answer. They are 1000 examples on youtube "how to make a login frm" but not in VB 2012 are by useing a selfmade database in VB.
So I already have a Bindingsource, Tableadapter, TableAdapterManager and a DatabaseDataSet en working with an tablegrid. Now I want to login to the system first before I get acces to the other parts of the program. The user have to write his name in to a textbox and when his names is existing (in the database), he get acces.
My problem is to check the column "users". What code can I use for that pleas?
Ideally You want the user to enter his/her username and password FIRST and then in the btnSubmit_Click event you should query the data source NEXT and check if the results are valid.
It is not recommended to load all the usernames/passwords and then look for a match.
It is `better/safer' to query ONLY for the single username/password pair.
This is not the EXACT code, but something along these lines.
Private Sub Submit_Click(sender As System.Object, e As System.EventArgs) Handles Submit.Click
'
If Trim(UsernameTextBox.Text) <> "" Then
If Trim(PasswordTextBox.Text) <> "" Then
'--> Query database here <--
'SELECT * From MyUsersSqlTable WHERE dbUsername='" trim(usernametextbox.text) & "' AND dbPassword='" & trim(passwordtextbox.text) & "'"
'If VALID Then
' Do something
'Else
' MsgBox("Error - Invalid login credentials")
' Do something else
'End If
Else
MsgBox("Error - No password entered")
End If
Else
MsgBox("Error - No username entered")
End If
'
End Sub
Obviously, you would not DIRECTLY enter the user entered data into a query, you should use parameters or VALIDATE the data to ensure it cannot inject something into your script!
You can check the username and password entered by the user with your table records. If both the fields match, it logins otherwise throws a message. However, you might also need to check case-sensitive password.
You can refer the following code.
Protected Sub SignIn(sender As Object, e As EventArgs) Handles btnsignin.ServerClick
Dim last_login As String
last_login = Now.Date.ToString("dd/MM/yy")
Try
conn.Close()
conn.Open()
Dim cmd As New MySqlCommand
cmd.CommandText = "SELECT * FROM user WHERE user_email = ('" & txtemail.Value.ToString & "') AND user_password=('" & txtpassword.Value.ToString & "') COLLATE utf8_bin"
cmd.Connection = conn
Dim da As New MySqlDataAdapter
Dim ds As New DataSet
da.SelectCommand = cmd
da.Fill(ds)
txtemail.DataBind()
txtpassword.DataBind()
Dim usercount = ds.Tables(0).Rows.Count
If usercount = 1 Then
reader = cmd.ExecuteReader
Session("user_email") = txtemail.Value.ToString
If reader.Read Then
Session("user_name") = reader.Item("user_name").ToString
'SetUserName(user_name)
Session("last_login") = reader.Item("last_login").ToString
str = "UPDATE user SET last_login = ('" & last_login.ToString & "') WHERE user_email = ('" & txtemail.Value.ToString & "') "
cmd = New MySqlCommand(str, conn)
reader.Close()
cmd.ExecuteNonQuery()
End If
Else
MsgBox("Incorrect email or password", MsgBoxStyle.Exclamation)
Return
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub

When selecting data from a database (SELECT * FROM) only last row is being read

I am making a create an account system, and in this I am using a SELECT * FROM query to read all of the data in the database to see if the inputted username already exists however this is only returning the very last user in the database, so if the inputted user matches any other user excluding the last saved account, it will not recognize that the user already exists therefore creating an account with the same username. Below is my code for the sub routine. can anyone please help me find what I have done wrong
Dim conn As New OleDbConnection
Dim myqry As String = Nothing
Dim mycmd As New OleDbCommand
Dim mydr As OleDbDataReader
Private Sub btn_createAccount_Click(sender As System.Object, e As System.EventArgs) Handles btn_createAccount.Click
'Connecting to the database
Try
With conn
If .State = ConnectionState.Open Then .Close()
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database.accdb"
.Open()
End With
Catch ex As Exception
MessageBox.Show("Unable to connect", "error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Dim student_Name As String
Dim student_Username As String
Dim student_Password As String
Dim student_Group As String
student_Name = txt_firstname.Text & " " & txt_surname.Text
student_Username = LCase(txt_Username.Text)
student_Password = txt_password.Text
student_Group = cbo_tutorGroup.SelectedItem
'This chunk of code is reading the username column in the student account table in my database and doing a read to see if the inputted username is already existent in the table.
myqry = "SELECT * FROM TblStudents"
mycmd = New OleDbCommand(myqry, conn)
mydr = mycmd.ExecuteReader
While mydr.Read
Dim user As String = mydr("studentUser").ToString
If user = student_Username Then
MsgBox("Username already exists, please choose another")
Else
'If the username is not taken, the account credentials will be stored for use when logging in
Dim sqlQry As String
sqlQry = "INSERT INTO TblStudents(studentName, tutorGroup, studentUser, studentPass) VALUES('" & student_Name & "','" & student_Group & "','" & student_Username & "','" & student_Password & "')"
Dim cmd As New OleDbCommand(sqlQry, conn)
cmd.ExecuteNonQuery()
MsgBox("Your account has successfully been created")
Login_Student.Show()
Me.Close()
Exit Sub
End If
End While
I think you are misinterpreting your results. The query may return many rows but if the first one does not match your condition (user = student_Username), then you insert a record and exit the procedure.
Why don't you check if your specific user exists:
SELECT * FROM TblStudents WHERE studentUser = :student_Username
instead of checking each student?

"There is no row at position 0"?

Private Sub BtnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLogin.Click
Dim sql As String
sql = " SELECT * FROM LoginDetails WHERE UsernameID = '" & TxtUsername.Text & "' AND Password = '" & TxtPassword.Text & "'"
ds = db.sqlSelect(sql)
Dim i As Integer
Dim Username As String = ds.Tables("LoginDetails").Rows(i)("UsernameID")
Dim Password As String = ds.Tables("LoginDetails").Rows(i)("Password")
''''''STUDENT LOGIN'''''''
If TxtUsername.Text = "" And TxtPassword.Text = "" Then
MsgBox("No username and password entered!")
ElseIf TxtUsername.Text = "" Then
MsgBox("No username entered!")
ElseIf TxtPassword.Text = "" Then
MsgBox("No password entered!")
End If
Username = TxtUsername.Text.ToLower
Password = TxtPassword.Text.ToLower
If TxtUsername.Text.ToLower = Username And TxtPassword.Text = Password Then
FrmMainMenu.Show()
Me.Hide()
FrmMainMenu.LblWelcome.Text = "Welcome " & ds.Tables("LoginDetails").Rows(i)("Student Name") & "!"
ElseIf TxtUsername.Text.ToLower = Username And TxtPassword.Text <> Password Then
MsgBox("Wrong password entered!")
End If
If TxtUsername.Text.ToLower <> Username And TxtPassword.Text <> Password Then
MsgBox("Wrong password or username!")
Else
End If
If Len(Username) <> 7 Then
MsgBox("Username must be exactly 7 characters long and must be in the following format: 1XlXXXX")
End If
If Len(Password) < 6 And Len(Password) > 30 Then
MsgBox("Password must be between 6 and 30 characters!")
End If
When I type in the correct details for the form it works, but whenever I type in say a wrong password, it crashes!
Can anyone help me solve this?? I keep getting this error!!!
IndexOutofRangeException was unhandled
There is no row at position 0.
Pointing at the code: Dim Username As String = ds.Tables("LoginDetails").Rows(i)("UsernameID")
Here is the class that links the code to my database:
Imports System.Data.OleDb
Public Class clsDBConnector
Dim con As New OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim da As OleDbDataAdapter
Dim ds As New DataSet
Sub connect()
dbProvider = "PROVIDER=MICROSOFT.ACE.OLEDB.12.0;"
dbSource = "Data Source = E:\Computing\COMP4\Database.accdb "
con.ConnectionString = dbProvider & dbSource
con.Open()
End Sub
Function sqlSelect(ByVal sqlString As String)
da = New OleDbDataAdapter(sqlString, con)
da.Fill(ds, "LoginDetails")
Return ds
End Function
Sub reset()
ds.Reset()
End Sub
Sub SQLinsert(ByVal sql) 'inserts data into database
Dim da As New OleDbCommand(sql, Con)
da.ExecuteNonQuery()
End Sub
Function SQLupdate(ByVal sqlString As String)
da = New OleDbDataAdapter(sqlString, con)
da.Fill(ds, "LoginDetails")
Return ds
End Function
End Class
The first thing you're doing wrong is storing plain-text passwords. Never store plain-text passwords.
The second thing is that you're wide open to SQL injection attack. Use parameterized queries. Otherwise you're allowing users to arbitrarily execute any code they'd like on your database.
The third thing is that you're assuming a returned value here:
sql = " SELECT * FROM LoginDetails WHERE UsernameID = '" & TxtUsername.Text & "' AND Password = '" & TxtPassword.Text & "'"
ds = db.sqlSelect(sql)
Dim i As Integer
Dim Username As String = ds.Tables("LoginDetails").Rows(i)("UsernameID")
Dim Password As String = ds.Tables("LoginDetails").Rows(i)("Password")
If that SELECT statement doesn't find any values, then Rows(i) (i is 0 in this case since that's the default for an Integer) doesn't exist. You need to check the count of Rows before trying to access it. In this case, logically, if Rows.Count is 0 then no match was found for the username/password combination, so the login fails. Notify the user that the login has failed and stop executing anything else.
The fourth thing you're doing wrong is storing plain-text passwords. Never store plain-text passwords.
Before you start using the dataset after the SQL call you should alway check to see if you received valid/any data back . Call a DataSet check method like the one I included. If it returns false you know your SQL returned an empty DataSet. So you can display a message stating invalid login info..
bool IsEmpty(DataSet dataSet)
{
foreach(DataTable table in dataSet.Tables)
{ if (table.Rows.Count != 0) return false; }
return true;
}
Every time you try to take information from the DB, with something like:
If ds.tables("MyTable").rowsCount > 0 then
// Do the stuff
Else
// There is no information on the table
End If

How to return database fields from checkbox selection?

the code below returns the fields of a given table ("Employee"), but I need to return the fields of ALL the tables in the given database, is this possible? My assumption is a For loop which loops round the tables in the database and prints the corresponding fields but my efforts seem to be in vain
Public Sub getDbFields()
Dim i As Integer
Dim dbcon As New System.Data.OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = " & dblocation & _
"\" & dbname)
Try
dbcon.Open()
dbDt = dbcon.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Columns, New Object() _
{Nothing, Nothing, "Employee", Nothing})
For i = 0 To dbDt.Rows.Count - 1
'compile lbtables with a list of available tables from the database
newLine()
frmMain.lstTables.Items.Add(dbDt.Rows(i)!COLUMN_NAME.ToString())
Next
Catch ex As Exception
MessageBox.Show(ex.Message.ToString(), "Data Load Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
End Try
End Sub
This routine will be fired from the selection of a checkbox
This will return all columns on a database
Using con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + dblocation + "\" + dbname)
con.Open()
Dim schema as DataTable = con.GetSchema("COLUMNS")
Dim dr as DataRow
For Each dr in schema.Rows
Dim tablename as string = dr("TABLE_NAME").ToString()
if Not tablename.StartsWith("MSys") then
Console.WriteLine(dr("TABLE_NAME").ToString() + " " + dr("COLUMN_NAME").ToString())
End if
Next
End Using
Please note that the bang (!) syntax is not allowed in vb.net.
Also your code could work if you change
dbDt = dbcon.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Columns, New Object() _
{Nothing, Nothing, Nothing, Nothing})
and this line
frmMain.lstTables.Items.Add(dbDt.Rows(i)("COLUMN_NAME").ToString())

Resources