I am trying to set user account for my system. I have two tables (User and Staff)
And this is the interface for setting up user
the name dropdownlist need to be bound to staff table where I can display a list of staff members. When I insert these data to the user table I need to convert the selected staff name into its ID.
I'm really weak in programming and if possible help me with this.
this is the code I am using
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnUserAdd.Click
If ValidData() Then
Try
cmd.Connection = con
con.Open()
sel_id = Convert.ToString(cmbStaffName.SelectedValue)
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert Into dbo.[User] (User_ID,Employee_ID,User_Name,Password,User_Level) values ('" & txtBoxUserID.Text & "','" & sel_id & "','" & txtBoxUserName.Text & "', '" & txtBoxPassword.Text & "','" & ComboBox1.Text & "')"
cmd.ExecuteNonQuery()
MsgBox("Succesfully Added", MsgBoxStyle.Information, "add")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
con.Close()
End If
If Not ValidData() Then
Exit Sub
End If
End Sub
Private Sub btnUserUpdate_Click(sender As Object, e As EventArgs) Handles btnUserUpdate.Click
End Sub
Private Sub Setup_User_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyHotelManagementSystemDataSet19.Staff' table. You can move, or remove it, as needed.
Me.StaffTableAdapter1.Fill(Me.MyHotelManagementSystemDataSet19.Staff)
'TODO: This line of code loads data into the 'MyHotelManagementSystemDataSet18.Staff' table. You can move, or remove it, as needed.
Me.User_TypeTableAdapter.Fill(Me.MyHotelManagementSystemDataSet17.User_Type)
End Sub
Private Sub cmbStaffName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStaffName.SelectedIndexChanged
Try
con.Open()
ds = New DataSet()
cmd = New SqlCommand("select * from Staff", con)
Adapter = New SqlDataAdapter(cmd)
adapter.Fill(ds)
cmbStaffName.DataSource = StaffBindingSource1
cmbStaffName.DisplayMember = "Name"
cmbStaffName.ValueMember = "Employee_ID"
Catch ex As Exception
Finally
con.Close()
End Try
End Sub
Private Sub cmbStaffName_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStaffName.SelectedIndexChanged
Try
con.Open()
ds = New DataSet()
cmd = New SqlCommand("select * from Staff", con)
Using adapter as New SqlDataAdapter(cmd)
adapter.Fill(ds)
End Using
cmbStaffName.DisplayMember = "Name"
cmbStaffName.ValueMember = "Employee_ID"
cmbStaffName.DataSource = ds
Catch ex As Exception
Finally
con.Close()
End Try
End Sub
Related
i want to update my datagridview and also my database im new to vb and i dont know what im doing wrong can sombody help me?
Private Sub DataGridView_Booking_Update(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView_Booking.RowLeave
Try
con.Open()
Using cmd As New SqlCommand("UPDATE Tbl_booking SET Omschrijving = #Omschrijving, Jaar = #Jaar, Opmerking = #Opmerking ,Sortnr = #Sortnr)", con)
cmd.Parameters.Add("#Omschrijving", SqlDbType.VarChar)
cmd.Parameters.Add("#Jaar", SqlDbType.Int)
cmd.Parameters.Add("#Opmerking", SqlDbType.VarChar)
cmd.Parameters.Add("#Sortnr", SqlDbType.Int)
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
MessageBox.Show("Error while updating record on table..." & ex.Message, "Update Records")
Finally
con.Close()
End Try
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDb.OleDbCommand("INSERT INTO table1(name,age,class) VALUES('John Legend','22','B.A Part 1')", con)
cmd.ExecuteNonQuery()
MsgBox("Record inserted successfully.")
con.Close()
Catch
MsgBox("Error Occured.")
End Try
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDb.OleDbCommand("update table1 set name='John DOE',age='23',class='12th' where id='1'", con)
cmd.ExecuteNonQuery()
MsgBox("Record Updated Successfully.")
con.Close()
Catch
MsgBox("Error Occured.")
End Try
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Try
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\database1.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDb.OleDbCommand("Delete from table1 where name='John DOE'", con)
cmd.ExecuteNonQuery()
MsgBox("Record Deleted Successfully.")
con.Close()
Catch
MsgBox("Error Occured.")
End Try
End Sub
Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
Me.Validate()
Me.dbDataAdapter.Update(Me.dbdataset.Tables("MyTable"))
Me.dbDataSet.AcceptChanges()
End Sub
hi I'm trying to insert a row to my database but I still get this error message (see below):
I used the methode using to be sure that the connection will be closed.
below the script for the insert button :
Private Sub MTB_Insert_Click(sender As Object, e As EventArgs) Handles MTB_Insert.Click
cmd = New SQLite.SQLiteCommand
Using con As New SQLite.SQLiteConnection(constr)
Try
'con.ConnectionString = constr
con.Open()
cmd.Connection = con
cmd.CommandText = "Insert Into Material_Type (Material_Type,Material_Type_Description) values(#Type,#Description)"
cmd.Parameters.AddWithValue("#Type", MTTB_Material_Type.Text)
cmd.Parameters.AddWithValue("#Description", MTTB_Material_Description.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Successful Added Data")
'Calling function load data
loadDatadg1()
'con.Dispose()
'con.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
other parts of my code :
Public Class F_Update
Dim con As SQLite.SQLiteConnection
Dim cmd As SQLite.SQLiteCommand
Dim da As SQLite.SQLiteDataAdapter
Dim constr As String = "Data source =Database1.db"
Public Sub loadDatadg1()
Using con As New SQLite.SQLiteConnection(constr)
'con = New SQLite.SQLiteConnection(constr)
con.Open()
Dim str As String = "select * from Material_type"
da = New SQLite.SQLiteDataAdapter(str, con)
Dim ds As New DataSet
da.Fill(ds, "Tb.Material_Type")
dg1.DataSource = ds.Tables("Tb.Material_Type")
'da.Dispose()
'con.Close()
End Using
End Sub
Private Sub F_Update_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Using con As New SQLite.SQLiteConnection(constr)
' con = New SQLite.SQLiteConnection(constr)
con.Open()
'MsgBox("OK")
'Calling the function Load form
loadDatadg1()
End Using
End Sub
another part :
Private Sub B_login_Click(sender As Object, e As EventArgs) Handles B_login.Click
Dim connectionString As String = "Data source =Database1.db"
Dim mSQL As String = "select User_Name,User_Password from User where (User_ID = 1 and User_Name = '" & T_User_Name.Text & "' and User_Password = '" & T_User_Password.Text & "')"
Dim dt As DataTable = Nothing
Dim ds As DataSet
Dim rd As SQLiteDataReader
Using con As New SQLiteConnection(connectionString)
Try
con.Open()
Dim cmd As New SQLiteCommand(mSQL, con)
cmd.ExecuteNonQuery()
rd = cmd.ExecuteReader
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If rd.HasRows Then
F_Update.Show()
Me.Close()
Else
MessageBox.Show("Invalid User Name or Password")
End If
'con.Close()
End Using
End Sub
End Class
can some one help me please ? Thanks in advance
This should be straight forward but it doesn't want to work for me..
I'm trying to populate a Datagridview on form load. The Sub below works fine if i call Populategrid() from a button once the grid is populate with the Reloadrecords & displayrecords.
Public Sub populategrid()
If Trim(Me.Text) = "CIMDETAILS" Then
da = New SqlDataAdapter("SELECT * from Interactions where [Name] like '" & txtdetect2.Text & "%' order by [IntDate] desc", SQLCon)
dsetAssets = New DataSet
da.Fill(dsetAssets, "Interactions")
dgvData.DataSource = dsetAssets.Tables("Interactions").DefaultView
Else
ReloadRecords()
DisplayRecords()
End If
Public Sub DisplayRecords()
Try
Dim da = New SqlDataAdapter("SELECT * from Interactions order by [IntDate] desc", SQLCon)
dsetAssets = New DataSet
da.Fill(dsetAssets, "Interactions")
dgvData.DataSource = dsetAssets.Tables("Interactions").DefaultView
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
End Try
End Sub
Sub ReloadRecords()
Try
FillCIM("SELECT * FROM Interactions order by [IntDate] desc", dgvData)
dgvData.Columns(0).Visible = False
dgvData.Columns(1).Width = 300 ''Name''
dgvData.Columns(1).HeaderCell.Value = "Customer Name"
dgvData.Columns(2).Width = 200 ''Int type''
dgvData.Columns(2).HeaderCell.Value = "Interaction Type"
dgvData.Columns(3).Width = 170 ''Int Date''
dgvData.Columns(3).HeaderCell.Value = "Interaction Date"
dgvData.Columns(4).Width = 400 ''Remarks''
dgvData.Columns(4).HeaderCell.Value = "Remarks"
dgvData.Columns(5).Visible = False
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
End Try
End Sub
Private Sub CIMDETAILS_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ReloadRecords()
DisplayRecords()
Call populategrid()
End Sub
Public Function FillCIM(ByVal Sqlstring As String, ByVal MyDataGrid As DataGridView)
Dim Constring = "Data Source=" & database & "\SQLEXPRESS; Initial Catalog = CIM; Integrated Security=true"
Dim SQLCon As New SqlConnection(Constring)
Dim SQLAdapter As New SqlDataAdapter()
Dim myDataset As New DataSet()
SQLCon.Open()
Try
SQLAdapter.SelectCommand = New SqlCommand(Sqlstring, SQLCon)
SQLAdapter.Fill(myDataset)
MyDataGrid.DataSource = myDataset.Tables(0)
Catch ex As Exception
End Try
SQLCon.Close()
SQLAdapter.Dispose()
myDataset.Dispose()
Return True
End Function
Pretty simple to get this working.
I've only just discovered there's an event after form load, which is form shown. Once i put the populategrid() sub in there it works fine.
Im working on a project. Our system is Hotel Reservation. In VB it says that it added in my database
but then when I check my database there is none.
What is the problem
btw Here's the code:
Public Class RegistrationForm
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
qry = "INSERT INTO tblGuest(GuestName, Gender, Address)VALUES('" &
txtName.Text & "','" &
txtGender.Text & "','" &
txtAddress.Text & "');"
cmd = New OleDb.OleDbCommand(qry, con)
dr = cmd.ExecuteReader()
MsgBox("Succesfully added in database")
RoomInfoForm.Show()
End Sub
Private Sub RegistrationForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
koneksyon()
End Sub
End Class
Just because your MsgBox fires doesn't mean the query did what you expect.
This is more like what you want to do:
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
'parameterize the query to avoid SQL injection attacks which is the #1 code vulnerability on OWASP Top 10
Dim qry As String = "INSERT INTO tblGuest(GuestName, Gender, Address)VALUES(?, ?, ?);"
'Put disposable resources within Using blocks
Using con As New OleDb.OleDbConnection()
Using cmd As New OleDb.OleDbCommand(qry, con)
'Create the parameters.
Dim paramName As New OleDb.OleDbParameter("#p1", OleDb.OleDbType.VarChar)
paramName.Value = txtName.Text 'you should null check and validate all these textbox values
Dim paramGender As New OleDb.OleDbParameter("#p2", OleDb.OleDbType.VarChar)
paramGender.Value = txtGender.Text
Dim paramAddress As New OleDb.OleDbParameter("#p3", OleDb.OleDbType.VarChar)
paramAddress.Value = txtAddress.Text
'Assign the parameters to the command
cmd.Parameters.Add(paramName)
cmd.Parameters.Add(paramGender)
cmd.Parameters.Add(paramAddress)
'you are not returning a result set from the command, so ExecuteNonQuery
cmd.ExecuteNonQuery()
End Using
End Using
MsgBox("Succesfully added in database")
RoomInfoForm.Show()
End Sub
I have a forum where I want the user to type a profile name and then click Add and then it will add what they typed in the text box the the ProfileName field in my table. When I click the Add button, it comes up with an error that says An unhandled exception of type System.Data.OleDb.OleDbException occurred in system.data.dll. Here is my code:
Private Sub RefreshData()
Dim cnn As New OleDb.OleDbConnection
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
Dim da As New OleDb.OleDbDataAdapter("SELECT id AS [ID], " & _
"ProfileName AS [Name] " & _
" FROM Profile ORDER BY id", cnn)
Dim dt As New DataTable
da.Fill(dt)
cnn.Close()
Me.dgvData.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (TextBox1.Text = "") Then
MsgBox("Please enter a profile name.")
Else
Dim cnn As New OleDb.OleDbConnection("Provider=Microsof… Source=c:\Data\Database.mdb ;Extended Properties=Paradox 5.x;")
Dim cmd As New OleDb.OleDbCommand
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
cmd.Connection = cnn
cmd.CommandText = "INSERT INTO Profile(ProfileName) " & _
"VALUES (" & Me.TextBox1.Text & "')"
cmd.ExecuteNonQuery()
cnn.Close()
Dim oForm As addsnake
oForm = New addsnake
oForm.Show()
oForm = Nothing
Me.Close()
End If
End Sub
Without further information I suggest that:
You don't need to give id an alias of ID:
SELECT id AS [ID]
you might still enclose it in square-brackets though, if you like:
SELECT [id]
You are missing an apostrophe in the following line:
"VALUES (" & Me.TextBox1.Text & "')"
Also check your connection string at connectionstrings.com