My question is somewhat complex but simple. I am building a small program to keep track of inventory. I created a view that contains a list of names and id in SQL. I then created a table so that I can add items to the names in SQL
IN vb.net
When the users clicks on the 1st datagridview - the name and number comes in separate text boxes. When they click the save button the records will then get saved to my table. (Which I have another Datagridview to show names and items. ) When I click my save button I get the following error:
Violation of PRIMARY KEY constraint 'PK_Inventory_Detail'. Cannot insert duplicate key in object 'dbo.Inventory_Detail'. The duplicate key value is (4 ).
I initially had the foreign key but then dropped based on the error but I am still getting it????
Imports System.Data.SqlClient
Public Class Form1
Dim cn As New SqlConnection("Data Source=;Initial Catalog=Inventory;User ID=;Password=")
Dim adap As New SqlDataAdapter("SELECT res_snbr, res_First_Name, res_Last_Name FROM ResidentInventoryView", cn)
Dim builder As New SqlCommandBuilder(adap)
Dim dt As New DataTable
Dim res_snbr As Object
'Dim InventoryDetailsBindingSource As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
' DataGridView1.AllowUserToAddRows = True
' DataGridView1.AllowUserToDeleteRows = True
DataGridView1.[ReadOnly] = False
'
adap.Fill(dt)
ResidentInventoryViewBindingSource.DataSource = dt
DataGridView1.DataSource = ResidentInventoryViewBindingSource
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If TextBox1.TextLength > 0 Then
ResidentInventoryViewBindingSource.Filter = String.Format("res_First_Name Like '%{0}%'", TextBox1.Text)
Else
ResidentInventoryViewBindingSource.Filter = String.Empty
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
adap.Update(dt)
MessageBox.Show("Saved successfully")
Catch ex As Exception
MessageBox.Show("Error updating database")
End Try
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Me.rlastname.Text = DataGridView1.Item(0, i).Value
Me.rfname.Text = DataGridView1.Item(1, i).Value
Me.rnum.Text = DataGridView1.Item(2, i).Value
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
cn.Open()
Dim cmd As New SqlCommand(("Insert INTO Inventory_Detail Values('" & _
rnum.Text & "','" & _
rfname.Text & "','" & _
rnum.Text & "','" & _
txtitem.Text & "','" & _
"" & "','" & _
"" & "')"), cn)
cmd.ExecuteNonQuery()
cn.Close()
MsgBox("Success....", MsgBoxStyle.Information, "Success")
rnum.Clear()
rfname.Clear()
rnum.Clear()
txtitem.Clear()
End Sub
End Class
You already have an item in the Inventory_Detail table with the id of 4. You need to increment the id so that every record in the Inventory_Detail table has a unique id.
You can you the Identity property in SQL to Increment your Primary Key so you don't have to insert the id manually.
Identity MSDN
Or Consider using a GUID that way it is always unique.
Right, so what I did ( maybe not the best)
created a view to get all names and ids
Created one table - contains a primary key that auto Increments
has an id field
item
start date
end date
The above will allow one person to be assigned multiple items and keep track of the items
Related
I have a dialog with a combobox listing the years an event was held.
Changing the year, changes the following list boxes
One list box 'called inEvent' shows all golfers the attended said event.
The other list box called 'available' that shows every golfer we have in our database that did not attend that years event
It has two buttons. One removes golfers from 'inEvent' and moves them to 'available'. This button works.
The other button does the opposite. It adds available golfers to the selected event year. But it gives me the error -
"The statement has been terminated. Cannot insert the value NULL into column 'intGolferEventYearID', table 'dbo.TGolferEventYears'; column does not allow nulls. INSERT fails."
Changing any line of code in VB results in a different error. So I think the error has to come from SQL itself which I don't know much about. Only other thing I can think of is the listbox is giving the wrong information.
Private Sub btnAddAuto_Click(sender As Object, e As EventArgs) Handles btnAddAuto.Click
Dim strInsert As String = ""
Dim cmdInsert As OleDb.OleDbCommand ' used for our Select statement
Dim dt As DataTable = New DataTable ' table we will load from our reader
Dim intRowsAffected As Integer
' open the DB
OpenDatabaseConnectionSQLServer()
' Build the select statement
strInsert = "INSERT INTO TGolferEventYears ( intGolferID, intEventYearID) Values (" & lstAvailable.SelectedValue & ", " & cboEvents.SelectedIndex + 1 & ")"
' Retrieve all the records
cmdInsert = New OleDb.OleDbCommand(strInsert, m_conAdministrator)
intRowsAffected = cmdInsert.ExecuteNonQuery()
' close the database connection and reload the form so the changes are shown
CloseDatabaseConnection()
frmEventsGolfers_Load(sender, e)
End Sub
I separated the data access code from the user interface. This will make it easy to remove data access entirely from the Form if you later desire.
Private Sub MoveGolfer(GolfID As Integer, YearID As Integer)
'If you keep your connections local you can be sure they are
'closed and disposed which is what the Using...End Using blocks do.
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("INSERT INTO TGolferEventYears ( intGolferID, intEventYearID) Values (#Golf, #Year;")
'Always use parameters to protect against Sql injection
cmd.Parameters.Add("#Golf", SqlDbType.Int).Value = GolfID
cmd.Parameters.Add("#Year", SqlDbType.Int).Value = YearID
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim GolferID As Integer = CInt(lstAvailable.SelectedValue)
Dim Year As Integer = cboEvents.SelectedIndex + 1
Try
MoveGolfer(GolferID, Year)
Catch ex As Exception
'Catch a more specific exception and handle accordingly
MessageBox.Show(ex.Message)
End Try
End Sub
Since I don't really understand SQL I didn't realize my PK didn't have the IDENTITY tag added in the table. Adding this fixed my issue.
Here is the code I added
Dim strSelect As String
Dim cmdSelect As OleDb.OleDbCommand
Dim drSourceTable As OleDb.OleDbDataReader
Dim intNextHighestRecordID As
strSelect = "SELECT MAX(intDealerAutos) + 1 AS intNextHighestRecordID " &
" FROM TDealerAutos"
'Excute command
cmdSelect = New OleDb.OleDbCommand(strSelect, m_conAdministrator)
drSourceTable = cmdSelect.ExecuteReader
'Read result( highest ID )
drSourceTable.Read()
'Null? (Empty Table)
If drSourceTable.IsDBNull(0) = True Then
'Yes, start numbering at 1
intNextHighestRecordID = 1
Else
'No, get the next highest ID
intNextHighestRecordID = CInt(drSourceTable.Item(0))
End If
'Build the select statement
strInsert = "INSERT INTO TDealerAutos ( intDealerAutos, intDealerID, intAutoID)" &
"Values (" & intNextHighestRecordID & ", " & cboDealers.SelectedValue & ", " & lstAvailable.SelectedValue & ")"
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
I have connected my DataGridView to a database but I can't implement the search function.
The flow of the program would be when I click one column of the DataGridView and I type in the search box, I can only get results from that same column not the other columns beside it.
It should also search letter by letter so basically a TextChanged event.
This is how i would do it
First, to have two variable to store your original datatable from database, and also a string variable to store your selected dgv column headertext (which will be used to do the filter later on).
Private oriDataTable As New DataTable
Private columnToFilter As String = String.Empty
My test on some dummy data
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'dummy datatable
oriDataTable.Columns.Add(New DataColumn("ID"))
oriDataTable.Columns.Add(New DataColumn("FirstName"))
oriDataTable.Columns.Add(New DataColumn("LastName"))
For i = 0 To 5
Dim dr As DataRow = oriDataTable.NewRow()
dr.Item("ID") = i
dr.Item("FirstName") = "fn type1 " & i
dr.Item("LastName") = "ln type1 " & i
oriDataTable.Rows.Add(dr)
Next
For i = 6 To 10
Dim dr As DataRow = oriDataTable.NewRow()
dr.Item("ID") = i
dr.Item("FirstName") = "fn type2" & i
dr.Item("LastName") = "ln type2" & i
oriDataTable.Rows.Add(dr)
Next
'Since you already connected to database
'i assume that you could fill a datatable and bind to dgv
dgvToFilter.DataSource = oriDataTable
columnToFilter = "ID" 'Assign any default column name
End Sub
Then add a ColumnHeaderMouseClick event handler on your dgv, update the columnToFilter each time when user click on it.
Private Sub dgvToFilter_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvToFilter.ColumnHeaderMouseClick
Dim clickedColumn As DataGridViewColumn = dgvToFilter.Columns(e.ColumnIndex)
'Note:HeaderText must match with your datatable column name
columnToFilter = clickedColumn.HeaderText
lblHeaderSelected.Text = columnToFilter
End Sub
And lastly the TextChaged Event. Use the DataTable.Select method to filter the datatable and update the result, if any, to the dgv.
Private Sub txtFilterText_TextChanged(sender As Object, e As EventArgs) Handles txtFilterText.TextChanged
If txtFilterText.Text.Length <= 0 Then dgvToFilter.DataSource = oriDataTable
Dim filterString = String.Format("{0} LIKE '{1}%'", columnToFilter, txtFilterText.Text)
Dim dataRows As DataRow() = oriDataTable.Select(filterString)
'Choose what you wan to do if no row is found. I bind back the oriDataTable.
dgvToFilter.DataSource = If(dataRows.Count > 0, dataRows.CopyToDataTable(), oriDataTable)
End Sub
You can try this.
Private Sub txtUname_TextChanged(sender As Object, e As EventArgs) Handles txtUname.TextChanged
dtaAdap = New SqlDataAdapter("Select * from tbl_user where Fname like '%" & txtUname.Text & "%'" & vbCrLf &
" OR Lname like '%" & txtUname.Text & "%'", con)
dt = New DataTable
dtaAdap.Fill(dt)
DataGridView1.DataSource = dt
End Sub
The query in SQLAdapter goes a little something like this:
Select * from <tbl_name> where <firstparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'
OR <secondparametercolumnname> like '%"& <your searchtexboxname.text here> &"%'
and so on depending on the number of fields you want to look at. Note: "con" is my SQLConnection.
This whole code snippet will fill your DatagridView with the result of the query everytime the user key in something on your searchtextbox.
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
how i bind multiple data from sql to label if i choose an item in combo box that is from sql this is my code:
Private Sub cmboCourse_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmboCourse.SelectedIndexChanged
If cmboCourse.Text = "ADVANCED COMPUTER TECHNICIAN" Then
callMe()
ElseIf cmboCourse.Text = "AUTOELECTRICITY" Then
callMe()
ElseIf cmboCourse.Text = "AUTOMOTIVE" Then
callMe()
End If
End Sub
Private Sub callMe()
Dim str As String = ("Data Source=PC1; User ID=sa; Password=pwd;Databasfriend")
Dim con As New SqlConnection(str)
Dim str1 As String = "SELECT * FROM tbl_course"
Dim da As New SqlDataAdapter(str1, con)
Dim dataset1 As New DataSet()
da.Fill(dataset1, "course")
lbl.DataBindings.Add("text", dataset1, "course.Course_Code")
end sub
and this is my table
Course_Code Course
ACT ADVANCED COMPUTER TECHNICIAN
AE AUTOELECTRICITY
AM AUTOMOTIVE
it binds only one data, i want to bind many data in a particular column example i choose a course AUTOMOTIVE in combo box how does course_code of AUTOMOTIVE binds to label and if i choose AUTOELECTRICITY how does course_code of AUTOELECTRICITY binds to the same label
This is not tested, let me know if it doesn't work.
Private Sub cmboCourse_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmboCourse.SelectedIndexChanged
callMe(cmboCourse.Text)
End Sub
Private Sub callMe(ByVal course as String)
Dim str As String = ("Data Source=PC1; User ID=sa; Password=pwd;Databasfriend")
Dim con As New SqlConnection(str)
Dim str1 As String = "SELECT * FROM tbl_course WHERE [Course]='" & course & "'"
Dim da As New SqlDataAdapter(str1, con)
Dim dataset1 As New DataSet()
da.Fill(dataset1, "tbl_course")
'lbl.DataBindings.Add("text", dataset1, "course.Course_Code")
If dataset1.Tables("tbl_course").Rows.Count > 0 Then
lbl.Text = dataset1.Tables("tbl_course").Rows(0)("Course_Code")
Else
MsgBox "Course [" & course & "] not found"
End If
End Sub
Please note that in your code, da.Fill(dataset1, "course") you specify the table to be 'course', while the select statement selects from 'tbl_course' table. I am assuming the latter is correct name.
Edit 1:
Bug fix
Edit 2:
Debugging
sc.Open()
Dim da As New SqlDataAdapter()
Dim dataset1 As New DataSet()
Dim sql As New SqlCommand("Select * from book where Title='" + cmbtit.Text + "'", sc)
da.SelectCommand = sql
da.SelectCommand.ExecuteNonQuery()
da.Fill(dataset1, "book")
If dataset1.Tables("book").Rows.Count > 0 Then
txtauthor.Text = dataset1.Tables("book").Rows(0)("Author")
Else
MsgBox("Author [" & cmbtit.Text & "] not found")
End If
sc.Close()
End Sub