Row not found in database using vb.net - vb.net

I am searching a row whose data is same as in my textbox1 but it shows the error as below.
Error snippet
Database Snippet
Code:
Imports System.Data.SqlClient
Imports WindowsApplication1.BBSRSDataSet1
Public Class CirricularDetails
Private Sub CirricularDetails_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Public Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
' Dim i As Integer
Dim a As String = "IEEE"
Dim x As Integer = 3
Try
databaseconnection()
Dim sql As String = "SELECT COUNT(*) AS rowscount FROM Curriculardb"
sqlinsertcommand = New SqlCommand(sql, connection)
Try
Dim count As Int16 = Convert.ToInt16(sqlinsertcommand.ExecuteScalar())
' BBSRSDataSet1.Tables(0).rows(count).cells(index2) = "TRUE" Then
MsgBox(count.ToString())
' For i = 0 To count - 1 Step 1 Field(Of CurriculardbDataTable)("IEEE")
Dim BBSRSDataSet1 = New BBSRSDataSet1
For i = 0 To count - 1
If BBSRSDataSet1.Tables("Curriculardb").Rows(1).ToString = TextBox1.Text Then
MsgBox("Record found")
End If
Next
Catch ex As SqlException
End Try
Catch ex As SqlException
End Try
End Sub

Related

Select from query not functioning

I just want to search data in my db but it is not functioning even if the data that I input in the textbox and comboBox has the correct data it keep show the else statement. it should be the else
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
searchWanted()
End Sub
Public Sub searchWanted()
Dim connString111 As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=bin\Debug\record.accdb"
MyConn111 = New OleDbConnection
MyConn111.ConnectionString = connString111
Try
Dim mySQLCommand As New OleDbCommand("select from * mostwanted where FIRSTNAME = #b0 and MIDDLENAME = #b1 and LASTNAME = #b2 and QLFR = #b3", MyConn111)
mySQLCommand.Parameters.AddWithValue("#b0", FIRSTNAMETextBox.Text)
mySQLCommand.Parameters.AddWithValue("#b1", MIDDLENAMETextBox.Text)
mySQLCommand.Parameters.AddWithValue("#b2", LASTNAMETextBox.Text)
mySQLCommand.Parameters.AddWithValue("#b3", QLFRComboBox.SelectedItem)
Dim da111 As New OleDbDataAdapter(mySQLCommand)
Dim table As New DataTable()
If table.Rows.Count() > 0 Then
MessageBox.Show("This Person is Wanted")
Dim picturedata As [Byte]() = table.Rows(0)(15)
Using ms As New MemoryStream(picturedata)
PHOTOPictureBox.Image = Image.FromStream(ms)
End Using
Else
MessageBox.Show("This Person is CLEAN")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

How do I multiply the value in the textbox and the column in listview?

See picI'm not familiar with vb.net. So, what I'm trying to do is when I click the chosen product and I put the qty. The Total price will show the multiplied value of the qty and price in the listview. I put the code in case 2 since it is the price but when I run it, it displays 0 then when I change it with a value of 2, it doesn't multiply. Here's my code so far:
Imports System.Data.SqlClient
Imports System.IO
Public Class Form2
Dim con As SqlConnection = New SqlConnection("server=.\SQL;database=try;Trusted_Connection=TRUE")
Dim cmd As SqlCommand
Dim cmd2 As SqlCommand
Dim rdr As SqlDataReader
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.Open()
con.Close()
list()
End Sub
Sub list()
con.Open()
cmd = New SqlCommand("SELECT * FROM ProductTable", con)
rdr = cmd.ExecuteReader
ListView1.Items.Clear()
If rdr.HasRows Then
Do While rdr.Read()
Dim arr As String() = New String(2) {}
Dim itm As ListViewItem
arr(0) = rdr("productID")
arr(1) = rdr("product")
arr(2) = rdr("price")
itm = New ListViewItem(arr)
ListView1.Items.Add(itm)
Loop
End If
con.Close()
End Sub
Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged
With Me.ListView1
Dim i As Integer
For Each item As ListViewItem In ListView1.SelectedItems
i = item.Index
Next
Dim innercounter As Integer = 0
For Each subItem As ListViewItem.ListViewSubItem In ListView1.Items(i).SubItems
Dim myString As String = ListView1.Items(i).SubItems(innercounter).Text
Select Case innercounter
Case 2
txtqty.Text = 0.ToString()
txtqty.Text = CType(0, String)
txtqty.Text = CStr(0)
txtqty.Text = "0"
txtprice.Text = myString * txtqty.Text
End Select
innercounter += 1
Next
End With
End Sub
End Class
You can have a Function to multiply values in Textbox and ListView
Private Function calculate() As Integer
Dim price As Integer
Dim qty As Integer
Dim totalPrice As Integer
Try
price = CInt(ListView1.Items(ListView1.FocusedItem.Index).SubItems(2).Text)
qty = CInt(txtqty.Text)
totalPrice = price * qty
Catch ex As Exception
MsgBox("Invalid Inputs!")
End Try
Return totalPrice
End Function
Convert the Strings into Integers so that you can multiply it. CInt() is the code for converting texts to int. Surround it by Try Catch to handle invalid inputs.
Then call the Function in your ListView1.SelectedIndexChanged or txtqty_TextChanged
Private Sub txtqty_TextChanged(sender As Object, e As EventArgs) Handles txtqty.TextChanged
txtprice.Text = calculate().ToString
End Sub
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
txtprice.Text = calculate().ToString
End Sub

The record cannot be deleted or changed because table 'Modules' includes related records

Having a problem with deleting records this exception keeps occurring.
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: The record cannot be deleted or changed because table 'Modules' includes related records.
Public Class frmStudentDatabase
Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=StudentDatabase.accdb")
Dim objStudentDA As New OleDb.OleDbDataAdapter("Select * From Students", objConnection)
Dim objStudentCB As New OleDb.OleDbCommandBuilder(objStudentDA)
Dim objDataSet As New DataSet()
Dim objModuleDA As New OleDb.OleDbDataAdapter("Select * From Modules", objConnection)
Dim objModuleCB As New OleDb.OleDbCommandBuilder(objModuleDA)
Private Sub frmStudentDatabase_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Call the sub procedure that will fill the dataset
'Create (Relationships) and Retrieve all Student_ID numbers
Retrieve()
End Sub
Private Sub cboStudents_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboStudents.SelectedIndexChanged
FillStudentDetails()
FillModuleDetails()
End Sub
Public Sub Retrieve()
objDataSet.Clear()
objStudentDA.FillSchema(objDataSet, SchemaType.Source, "Students")
objStudentDA.Fill(objDataSet, "Students")
objModuleDA.FillSchema(objDataSet, SchemaType.Source, "Modules")
objModuleDA.Fill(objDataSet, "Modules")
objDataSet.Relations.Clear()
objDataSet.Relations.Add("Students2Modules", objDataSet.Tables("Students").Columns("Student_ID"), _
objDataSet.Tables("Modules").Columns("Student_ID"))
'Empty combo box
cboStudents.Items.Clear()
'Loop through each row, adding the Student_ID to the combobox
Dim i As Integer, strCurrentID As String
For i = 1 To objDataSet.Tables("Students").Rows.Count
strCurrentID = objDataSet.Tables("Students").Rows(i - 1).Item("Student_ID")
cboStudents.Items.Add(strCurrentID)
Next
'Select first item in the list
cboStudents.SelectedIndex = 0
FillStudentDetails()
FillModuleDetails()
End Sub
Public Sub FillStudentDetails()
Dim objRow As DataRow
objRow = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem)
txtStudentID.Text = objRow.Item("Student_ID")
txtStudentName.Text = objRow.Item("Student_Name")
txtStudentAddress.Text = objRow.Item("Student_Address")
End Sub
Public Sub FillModuleDetails()
Dim objStudent As DataRow, objModule As DataRow
Dim strModuleEntry As String
'Clear any existing modules
lstModules.Items.Clear()
'Find the current student record
objStudent = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem.ToString)
For Each objModule In objStudent.GetChildRows("Students2Modules")
strModuleEntry = objModule.Item("Module_ID") & "," & objModule.Item("Module_Name") &
"," & objModule.Item("Module_Desc")
lstModules.Items.Add(strModuleEntry)
DataGridView1.DataSource = objDataSet.Tables("Modules")
Next
End Sub
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
Dim objRow As DataRow
Dim objRowModules As DataRow
Dim RowIndex As Integer
objRow = objDataSet.Tables("Students").NewRow
objRow.Item("Student_Name") = InputBox("Please Enter Student Name:")
objRow.Item("Student_Address") = InputBox("Please Enter Student Address:")
'Add data row to table
objDataSet.Tables("Students").Rows.Add(objRow)
objStudentDA.Update(objDataSet, "Students")
'Set up the module data row object
objRowModules = objDataSet.Tables("Modules").NewRow
'Find the number of the last row
RowIndex = objDataSet.Tables("Students").Rows.Count - 1
'Tell vb.net to get the Student_ID value from the last row
objRowModules.Item("Student_ID") = objDataSet.Tables("Students").Rows(RowIndex)("Student_ID")
objRowModules.Item("Module_Name") = InputBox("Please Enter Module Name:")
objRowModules.Item("Module_Desc") = InputBox("Please Enter Module Description:")
'Add to the DB
objDataSet.Tables("Modules").Rows.Add(objRowModules)
'Update the data adapter
objModuleDA.Update(objDataSet, "Modules")
MessageBox.Show("New record saved", "Saved")
Retrieve()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'Code to modify an existing record
Dim objRowCurrent As DataRow
objRowCurrent = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem.ToString)
'We cannot modify the ID as it is an AutoNumber
objRowCurrent("Student_Name") = txtStudentName.Text
objRowCurrent("Student_Address") = txtStudentAddress.Text
objStudentDA.Update(objDataSet, "Students")
objDataSet.AcceptChanges()
'Now that we made changes, we need to retrieve the new data
Retrieve()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Dim i As integer, strCurrentID As String
Dim StudentName As String
Dim StudentFound As Boolean = False
StudentName = InputBox("Enter a Name Please!", "Search")
For i As Integer = 0 To (objDataSet.Tables("Students").Rows.Count - 1)
If CStr(objDataSet.Tables("Students").Rows(i)("Student_Name")) = StudentName Then
StudentFound = True
cboStudents.SelectedIndex = i
FillStudentDetails()
FillModuleDetails()
End If
Next
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
Dim rowIndex As Integer = cboStudents.SelectedItem - 1
If (rowIndex < objDataSet.Tables("Students").Rows.Count - 1) Then
rowIndex = rowIndex + 1
cboStudents.SelectedIndex = rowIndex
FillStudentDetails()
FillModuleDetails()
Else
MessageBox.Show("No more records to display", "End")
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim objRow As DataRow
objRow = objDataSet.Tables("Students").Rows.Find(txtStudentID.Text)
'Remember that all related child rows will be deleted! So no need to
'set up a new datarow for the Pet table
objRow.Delete()
objStudentDA.Update(objDataSet, "Students")
Retrieve()
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
Dim rowIndex As Integer = cboStudents.SelectedItem - 1
If (rowIndex > 0) Then
rowIndex = rowIndex - 1
cboStudents.SelectedIndex = rowIndex
FillStudentDetails()
FillModuleDetails()
Else
MessageBox.Show("No more records to display", "Start")
End If
End Sub
End Class
You try to remove a record which has child records. Due to those references your removal fails. The reason is that the Student has Modules. You will need to remove the references to the Student before you can remove it.

Auto-fill textbox on a dialog form, from a Datagridview on the original form, vb.net 2013

I am currently working in windows form applications using vb.net 2013. I have two forms, we can call them form1 and form 2 for now. Form1 has a datagridview with a checkbox column that the end user will click to open form2 as a dialog form. Once form2 opens I want it to automatically load and fill two text boxes that have information from corresponding columns from the original DGV. In short, the DGV on form1 has 3 columns; JobNumber, LineNumber, and the checkbox. The end user will click the checkbox to bring up form2 and I want the Jobnumber and Linenumber to automaticaly fill into two textboxes on form2. Here is my code from form1.
'assembly dialog result form
dr = f.ShowDialog
If dr = Windows.Forms.DialogResult.OK Then
'dim y as job string
Dim Y As String = DataGridOrdered.Rows(e.RowIndex).Cells(3).Value
'open connection
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET Complete = 1, RackIn = 1 WHERE JobNumber = '" & Y & "'", conn1)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Call DGVOrderedRefresh()
ElseIf dr = Windows.Forms.DialogResult.Yes Then
'dim M as job string
Dim M As String = DataGridOrdered.Rows(e.RowIndex).Cells(3).Value
'open connection
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET Complete = 1, RackIn = 1 WHERE JobNumber = '" & M & "'", conn1)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Call DGVOrderedRefresh()
ElseIf dr = Windows.Forms.DialogResult.Cancel Then
'refresh datagridview ordered
Call DGVOrderedRefresh()
End If
ElseIf e.ColumnIndex = 0 Then
'fail safe to make sure the header is not clicked
If e.RowIndex = -1 Then
Exit Sub
End If
The code for my dialog is as follows
Imports System.Data
Imports System.Data.SqlClient
Public Class BuildName
' Dim connstring As String = "DATA SOURCE = BNSigma\CORE; integrated security = true"
Dim connstring As String = "DATA SOURCE = BNSigma\TEST; integrated security = true"
Private Sub Label3_Click(sender As Object, e As EventArgs) Handles Label3.Click
End Sub
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ds As New DataTable
Try
'load name combo box
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("SELECT Name FROM Production.dbo.FCNames", conn1)
Dim adapater As New SqlDataAdapter
adapater.SelectCommand = comm1
adapater.Fill(ds)
adapater.Dispose()
conn1.Close()
CBName.DataSource = ds
CBName.DisplayMember = "Name"
CBName.ValueMember = "Name"
End Using
End Using
Catch ex As Exception
MsgBox("Error loading name List, please contact a mfg. Engr.!")
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Update built by name
Dim v As Object = TBFloor.Text
Dim G As Object = TBLine.Text
Dim O As Object = TBJobNumber.Text
Try
Using conn1 As New SqlConnection(connstring)
conn1.Open()
Using comm1 As SqlCommand = New SqlCommand("UPDATE Production.dbo.tblFCOrdered SET BuiltBy = #Name Where JobNumber = '" & O & "'", conn1)
comm1.Parameters.AddWithValue("#Name", CBName.Text)
comm1.ExecuteNonQuery()
conn1.Close()
End Using
End Using
Catch ex As Exception
MsgBox("Error updating Ordered table, please contact a MFG. ENGR.!")
MsgBox(ex.ToString)
End Try
End Sub
End Class
UPDATED CODE FOR VALTER
Form1 code
Public row_Index As Integer = 0
Private Sub DataGridOrdered_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridOrdered.CurrentCellDirtyStateChanged
If DataGridOrdered.IsCurrentCellDirty Then
DataGridOrdered.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
Private Sub DataGridOrdered_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridOrdered.CellValueChanged
If DataGridOrdered.Columns(e.ColumnIndex).Name = 9 Then
Dim checkCell As DataGridViewCheckBoxCell = CType(DataGridOrdered.Rows(e.RowIndex).Cells(9), DataGridViewCheckBoxCell)
If CType(checkCell.Value, [Boolean]) = True Then
row_Index = e.RowIndex
BuildName.ShowDialog(Me)
End If
End If
End Sub
Form 2 code
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.DataGridOrdered.Rows(FormOrdered.row_Index).Cells(3).Value
Dim value2 As Object = FormOrdered.DataGridOrdered.Rows(FormOrdered.row_Index).Cells(4).Value
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
In your form1 add:
Public Row_Index As Integer = 0 //use a simple variable
Sub datagridOrdered_CurrentCellDirtyStateChanged( _
ByVal sender As Object, ByVal e As EventArgs) _
Handles datagridOrdered.CurrentCellDirtyStateChanged
If datagridOrdered.IsCurrentCellDirty Then
datagridOrdered.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
End Sub
Private Sub datagridOrdered_CellValueChanged(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles datagridOrdered.CellValueChanged
If datagridOrdered.Columns(e.ColumnIndex).Name = "Assemble" Then //<- here
Dim checkCell As DataGridViewCheckBoxCell = _
CType(datagridOrdered.Rows(e.RowIndex).Cells(2), _ //<- here
DataGridViewCheckBoxCell)
If CType(checkCell.Value, [Boolean]) = True Then
//RowIndex = e.RowIndex you dont need this
Row_Index = e.RowIndex
BuildName.ShowDialog(Me)
End If
End If
End Sub
//Nor this
//Private _count As Integer
//Public Property RowIndex() As Integer
//Get
//Return _count
//End Get
//Set(value As Integer)
//_count = value
//End Set
//End Property
And in dialog load event use Form1.Row_Index instead:
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.datagridOrdered.Rows(Form1.Row_Index).Cells(0).Value //<- here
Dim value2 As Object = FormOrdered.datagridOrdered.Rows(Form1.Row_Index).Cells(1).Value //<- here
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
...
...
End Sub
or add a module and add the Row_Index there. You can use it then as is
Private Sub BuildName_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim value1 As Object = FormOrdered.DataGridView1.Rows(Row_Index).Cells(0).Value
Dim value2 As Object = FormOrdered.DataGridView1.Rows(Row_Index).Cells(1).Value
TBJobNumber.Text = CType(value1, String)
TBFloor.Text = CType(value2, String)
...
...
End Sub

How to remove data row from data table base on column name with primary key

I would like to remove data row from datantable in vb.net.
When I find the row based on column with primary key, it return error . I google but cannot resolve the error .
This is my code
Private Sub frmMatching_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dtFromCustomer = New DataTable()
dtToCusotmer = New DataTable()
dtTemp = New DataTable()
SetColumn()
BindFromCustomer()
BindToCustomer()
End Sub
Private Sub SetColumn()
Dim keyColumn As New DataColumn()
keyColumn.ColumnName = "CV_CODE"
keys(0) = keyColumn
dtFromCustomer.Columns.Add(keyColumn)
dtFromCustomer.Columns.Add("CV_NAME")
dtFromCustomer.PrimaryKey = keys
End Sub
Private Sub BindFromCustomer()
Dim ds As New DataSet
ds.Clear()
ds = GetDataset(sql)
Try
If ds.Tables(0).Rows.Count > 0 Then
dtFromCustomer = ds.Tables(0)
dtFromCustomer.PrimaryKey = Nothing
Dim col As DataColumn = dtFromCustomer.Columns("CV_CODE")
dtFromCustomer.AcceptChanges()
gvFromCustomer.DataSource = dtFromCustomer
End If
End Sub
Private Sub btnAddOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddOne.Click
If gvFromCustomer.SelectedRows.Count > 0 And dtFromCustomer.Rows.Count > 0 Then
Dim dr As DataRow
Dim i As Integer = 0
Try
Dim foundRow As DataRow
Dim findThese(0) As Object
findThese(0) = gvFromCustomer.SelectedRows(0).Cells("CV_CODE").Value.ToString()
foundRow = dtFromCustomer.Rows.Find(findThese)
If Not (foundRow Is Nothing) Then 'row is found
dtFromCustomer.Rows.Remove(foundRow)
Exit Sub
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
dtFromCustomer.AcceptChanges()
gvFromCustomer.DataSource = dtFromCustomer
gvToCustomer.Refresh()
End If
My error get this line
foundRow = dtFromCustomer.Rows.Find(findThese)