how to send a multiple message using datagridview in selecting a checkbox in vb.net? - vb.net

Here is my code:
'for clicking the datagridview
Private Sub DataGridView1_CellContentClick_1(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Try
MySqlConnection.ConnectionString = "Server=localhost; User=root;Password='';Database=lrbhams;"
MySqlConnection.Open()
Dim state3 As String = "select boarder_fname, boarder_contact, guardian, guardian_number from boarders_info"
Dim command As New MySqlCommand(state3, MySqlConnection)
'command.Connection.Open()
command.ExecuteNonQuery()
MySqlConnection.Close()
If DataGridView1.Rows(e.RowIndex).Cells(2).Value Then
TextBox1.Text = DataGridView1.Rows(e.RowIndex).Cells(2).Value
ElseIf DataGridView1.Rows(e.RowIndex).Cells(4).Value Then
TextBox1.Text = DataGridView1.Rows(e.RowIndex).Cells(4).Value
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
''
End Sub
For sending message:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim message As String
'Dim reader As MySqlDataReader
message = RichTextBox1.Text
If send_sms.SerialPort.PortName = send_sms.portName Then
send_sms.SerialPort.Write("AT" & vbCrLf)
send_sms.SerialPort.Write("AT+CMGF=1" & vbCrLf)
send_sms.SerialPort.Write("AT+CMGS=" & Chr(34) & TextBox1.Text & Chr(34) & vbCrLf)
send_sms.SerialPort.Write(message & Chr(26))
MsgBox("Text Message Successfully Send !!!")
Try
Dim connectString As String
Dim conn As New MySqlConnection
Dim reader As MySqlDataReader
Dim command As MySqlCommand
'Dim mysqlQuery As String
connectString = "server=localhost;user=root;database=lrbhams"
conn = New MySqlConnection(connectString)
Dim query As String
conn.Open()
query = "INSERT into admin_log_attendance (action,contact_number, date) VALUES ('" & RichTextBox1.Text & "','" & TextBox1.Text & "', '" & Date.Today & "')"
command = New MySqlCommand(query, conn)
reader = Command.ExecuteReader
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub

MySqlConnection is a class in the MySql.Data.MySqlClient namespace. It is not a static class so it must be instantiated with the New keyword. You cannot set properties or call methods on the class itself. You must created an instance of the class. It is best practice to use `Using...End Using blocks for database objects. It will ensure that the database objects are closed and disposed even if there is an error.
A Select statement is not a NonQuery. Insert, Update and Delete statements can be run with command.ExecuteNonQuery but not Select. A Select query can be run with .ExecuteScalar if a single piece of data is expected or .ExecuteReader if several columns and/or rows are expected.
You can't just execute a Select command and expect something to happen. I suspect you want to display the data in your grid so let's fill a DataTable (an in memory representation of the records returned) with the .Load method then bind it to the DataGridView.
No need to close the connection because the Using block will close it.
If you call .ToString on a class that doesn't override the method you will just get the fully qualified name of the class. The Exception class provides a Property called Message which you can use.
The filling of the DataGridView will go in a separate method which you can call from Form.Load.
Now that there is data in the DataGridView you can click on it and the CellContentClick event will fire. I hope Cell(2) and Cell(4) Booleans because that is the only why your If statement will work. The necessity of the conversion code and .ToString will be obvious once you turn on Option Strict. (See my comment)
That's enough for now. With all this and Option Strict you should be able to fix the second part of your code.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RetrieveRecordsForDataGridView()
End Sub
Private Sub RetrieveRecordsForDataGridView()
Dim dt As New DataTable
Try
Using cn As New MySqlConnection("Server=localhost; User=root;Password='';Database=lrbhams;")
Dim state3 As String = "select boarder_fname, boarder_contact, guardian, guardian_number from boarders_info"
Using command As New MySqlCommand(state3, cn)
cn.Open()
dt.Load(command.ExecuteReader())
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If CBool(DataGridView1.Rows(e.RowIndex).Cells(2).Value) Then
TextBox1.Text = DataGridView1.Rows(e.RowIndex).Cells(2).Value.ToString
ElseIf CBool(DataGridView1.Rows(e.RowIndex).Cells(4).Value) Then
TextBox1.Text = DataGridView1.Rows(e.RowIndex).Cells(4).Value.ToString
End If
End Sub

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

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

Problem with Windows Form and Access Database

First post here. I'm actually new to the world of programming and what I ask could look silly to many of you.
Anyway I'm trying to create a Form that will search into a Database the name you're looking for, showing a list of information about that person.
Problem comes when there's more than one person with that name in the database: in that case, the form only shows one of them. I wanted to add a button to get to the next result, but that's where I'm stuck.
I looked on the web for similar problems, but couldn't find any.
Here's my code, hope someone could help me
(please keep in mind I'm new and I don't know much about programming yet).
Form1:
Private Sub BtnCerca_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnCerca.Click
Dim trova As Boolean
Try
cm = New OleDb.OleDbCommand
With cm
.Connection = cn
.CommandType = CommandType.Text
.CommandText = "SELECT * FROM persone WHERE nome = '" & txtSearch.Text & "' OR cognome = '" & txtSearch.Text & "'"
dr = .ExecuteReader
End With
While dr.Read()
txtId.Text = dr("id_persone").ToString
txtNome.Text = dr("nome").ToString
txtCognome.Text = dr("cognome").ToString
txtDate.Text = dr("data_nascita").ToString
txtNascita.Text = dr("luogo_nascita").ToString
txtResidenza.Text = dr("luogo_residenza").ToString
trova = True
End While
If trova = False Then Dim unused = MsgBox("UTENTE NON TROVATO!", MsgBoxStyle.Critical)
dr.Close()
Catch ex As Exception
End Try
Exit Sub
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Call Connection()
End Sub
Private Sub BtnReset_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnReset.Click
ClearTextFields(Me)
End Sub
Public Sub ClearTextFields(ByVal parent As Control)
For Each ctl As Control In parent.Controls
If TypeOf ctl Is TextBox Then
If ctl.Text.Trim() <> String.Empty Then
ctl.Text = String.Empty
End If
End If
Next
End Sub
End Class
Module:
Imports System.Data.OleDb
Module modConnection
Public cn As New OleDb.OleDbConnection
Public cm As New OleDb.OleDbCommand
Public dr As OleDbDataReader
Public Sub Connection()
cn = New OleDb.OleDbConnection
With cn
.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath & "\dati_persone.mdb"
.Open()
End With
End Sub
End Module
In the form design view, drag and drop the BindingNavigator onto your form. You will find this in the Toolbox under the Data node. You can remove the + button and the X button by right clicking and choosing Delete from the context menu.
We will use a DataTable since that can be used as a DataSource for the BindingSource.
Keep your data objects local to the method where they are used so you can be sure they are closed and disposed. A Using block takes care of this for you. The Using block here includes both the connection and the command.
Always use parameters to avoid sql injection which can damage your database.
Create a BindingSource and set its DataSource to the DataTable. Then set the BindingSource property of the BindingNavigator you added to the form. Next add the DataBindings to each of your text boxes. The .Add method takes the name of the property to bind to, the BindingSource, and the field name.
That should do it.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Try
Using cn As New OleDbConnection("your connection string"),
cmd As New OleDbCommand("Select * From persone Where nome = #nome Or cognome = #cognome;", cn)
cmd.Parameters.Add("#nome", OleDbType.VarChar).Value = txtSearch.Text
cmd.Parameters.Add("#cognome", OleDbType.VarChar).Value = txtSearch.Text
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Dim BdS As New BindingSource
BdS.DataSource = dt
BindingNavigator1.BindingSource = BdS
txtId.DataBindings.Add("Text", BdS, "id_persone")
txtNome.DataBindings.Add("Text", BdS, "nome")
txtCognome.DataBindings.Add("Text", BdS, "cognome")
txtDate.DataBindings.Add("Text", BdS, "data_nascita")
txtNascita.DataBindings.Add("Text", BdS, "luogo_nascita")
txtResidenza.DataBindings.Add("Text", BdS, "luogo_residenza")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

VB.net/MS Access Monthly Donations System Assistance

I'm doing a project for my Database Management subject. I cannot figure out how to add an amount to a previously added amount. For now, I'm only able to update the amount. Here's the code. I'm sorry if I cannot explain it well.
I have 2 forms. My first form allows me to enter a last name and retrieve the data to my list view.
My second form lets me retrieve the data I entered in my first form and it will show up on a separate list view with a "Last Name | Amount" tab.
I have two textboxes. One for last name set to readonly to disable editing, and another for the amount I want to enter.
After entering an amount, let's say 20, it will update on the listview and my database as 20.
The problem is that when I enter a new amount for the same last name, let's say 30, the 30 will replace the 20 but it should be 50 because 20+30 = 50.
I understand the logic and I have tried adding another textbox for addition but I simply do not know the codes for it.
Imports System.Data.OleDb
Public Class Form2
Dim conString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Israel De Leon\Documents\testing.accdb;"
Dim con As OleDbConnection = New OleDbConnection(conString) 'Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database2.accdb
Dim cmd As OleDbCommand
Dim adapter As OleDbDataAdapter
Dim dt As DataTable = New DataTable()
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'SET LISTVIEW PROPERTIES
ListView1.View = View.Details
ListView1.FullRowSelect = True
'Construct Columns
ListView1.Columns.Add("Last Name", 100)
ListView1.Columns.Add("Amount", 100)
End Sub
Private Sub UpdateLV(lname As String)
'Updates last name and amount entered into the database
Dim sql As String = "UPDATE Table1 SET LastName='" + TextBox1.Text + "',Amount='" + TextBox2.Text + "' WHERE LastName='" + lname + "'"
cmd = New OleDbCommand(sql, con)
'OPEN CON, EXECUTE, UPDATE, CLOSE
Try
con.Open()
adapter = New OleDbDataAdapter(cmd)
adapter.UpdateCommand = con.CreateCommand()
adapter.UpdateCommand.CommandText = sql
If (adapter.UpdateCommand.ExecuteNonQuery() > 0) Then
MsgBox("Successfully Updated")
End If
con.Close()
Retrieve()
ClearBox()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub Retrieve()
ListView1.Items.Clear()
'SQL STM
Dim sql As String = "SELECT * FROM Table1 "
cmd = New OleDbCommand(sql, con)
'OPEN CON, RETRIEVE, FILL LISTVIEW
Try
con.Open()
adapter = New OleDbDataAdapter(cmd)
adapter.Fill(dt)
'LOOP THROUGH DT
For Each row In dt.Rows
Populate(row(0), row(1)) 'Index of database row
Next
'CLEAR DATATABLE
dt.Rows.Clear()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Private Sub Populate(lname As String, aamount As String)
'ROW ARRAY
Dim row As String() = New String() {lname, aamount}
Dim item As ListViewItem = New ListViewItem(row)
'ADD TO ROWS COLLECTION
ListView1.Items.Add(item)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Retrieve()
End Sub
Private Sub ListView1_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView1.MouseClick
Dim llname As String = ListView1.SelectedItems(0).SubItems(0).Text
Dim amounts As String = ListView1.SelectedItems(0).SubItems(1).Text
TextBox1.Text = llname
TextBox2.Text = amounts
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim amounts As String = ListView1.SelectedItems(0).SubItems(0).Text
UpdateLV(amounts)
End Sub
Private Sub ClearBox()
TextBox1.Text = ""
TextBox2.Text = ""
End Sub
End Class
Mathematical operation should not be done using strings. This is a real basic principle that many VB.NET programmers don't think enough thanks to the forgiveness allowed by Option Strict Off in the VB.NET project settings.
If you are just starting a new project in VB.NET don't use this setting but switch it ASAP to On. This will give you an halt when you try to use strings as they were numbers and force you to do the appropriate conversion and checking on the values provided.
So your code that updates the amount rewritten
Private Sub UpdateLV(lname As String)
' Get the amount as a number (decimal for currency is the best)
Dim addAmt As Decimal
if Not decimal.TryParse(textbox2.Text, addAmt) Then
MessageBox.Show("Insert a valid amount please")
return
End If
' Sanity check
if addAmt <= 0 Then
MessageBox.Show("Amount should be > 0")
return
End If
'Updates last name and amount entered into the database
Dim sql As String = "UPDATE Table1 SET LastName=#name
,Amount=Amount+#amt
WHERE LastName=#oldname"
cmd = New OleDbCommand(sql, con)
Try
con.Open()
' Using an adapter here is wrong. You use directly the command
cmd.Parameters.Add("#name", OleDbType.VarWChar).Value = textBox1.Text
cmd.Parameters.Add("#amt", OleDbType.Decimal).Value = addAmt
cmd.Parameters.Add("#oldname", OleDbType.VarWChar).Value = lName
If (cmd.ExecuteNonQuery() > 0) Then
MsgBox("Successfully Updated")
End If
con.Close()
Retrieve()
ClearBox()
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
Something else is not clear in your code. What is the purpose of changing also the LastName here? Finally do not keep a global connection object. Instead create it when you need it and destroy it afterward with Using statement. It will be better for your memory footprint and for your database

How to view data from database in a new page after successfully logged in

I am trying to figure out how to automatically display user data from database in a new page after they're successfully logged in using VB.
Imports MySql.Data.MySqlClient
Public Class guardianlogin
Dim MySqlConn As New MySqlConnection
Dim reader As MySqlDataReader
Dim command As MySqlCommand
Private Sub ManageCustomer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MySqlConn.ConnectionString = "server=localhost ; user id=root ; password = '1234' ; database = 'bengkel1_farah' "
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
MySqlConn.Open()
Dim Query As String
Query = "select * from guardian where g_ID ='" & TextBox1.Text & "' and password ='" & TextBox2.Text & "'"
command = New MySqlCommand(Query, MySqlConn)
reader = command.ExecuteReader
Dim count As Integer
count = 0
While reader.Read
count = count + 1
End While
If count = 1 Then
guardianview.Show()
Me.Hide()
TextBox1.Clear()
TextBox2.Clear()
Else
MessageBox.Show("YOUR USERNAME OR PASSWORD ARE INCORRECT. PLEASE TRY AGAIN")
TextBox1.Clear()
TextBox2.Clear()
End If
MySqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MySqlConn.Dispose()
End Try
End Sub
what should I add or remove to my coding?
I'm guessing that your guardianlogin class is used to simply validate the user login and your guardianview is used to display the data from the database?
If that is right them you need to put your labels on your guardianview form and update the labels before showing the form.
guardianview.Load()
guardianview.lblUsername.text = USERNAME_DATA_FROM_DATABASE_HERE
guardianview.lblPassword.text = PWD_DATA_FROM_DATABASE_HERE
guardianview.lblAdminMsg.text = MESSAGE_DATA_FROM_DATABASE_HERE
guardianview.Show()
Me.Hide()
I am assuming guardianview.Show() is the page you are trying to show your user's data. So basically you just create some labels and retrieve some strings/integers from your MySql database. Here's some codes, that may give you a better understanding.
Try
MysqlConn.Open()
Dim Query As String
Query = "select * from bengkel1_farah.guardian where g_ID='" & Form1.TextBox1.Text & "'"
command = New MySqlCommand(Query, MysqlConn)
reader = command.ExecuteReader
While READER.Read
Label15.Text = READER.GetInt32("ID") 'You use GetInt32 to get integers
Label31.Text = READER.GetString("Name") 'You use GetString to get strings
Label23.Text = READER.GetString("Email")
End While
MysqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
I tried to be clear enough, anyway if you still face troubles, I will try to explain more.