Retrieving data from ListView control in VB.NET - database

I have a ListView setup in details mode that looks like this:
When the user presses the delete button, I need to go ahead and delete their record from the database. This I can do fine, but I'm stuck on how I retrieve the data that is highlighted in the ListView control. I've tried using Google but all the examples I found have failed to work.
Can someone help me out here?

You should be able to get the underlying object by using:
ListView1.SelectedItems(0)
Once you remove it from the database you should rebind the data.

Dim name, room, subject, date, period As String
If listviewName.SelectedItems.Count > 0 then
'*********** transfer selected data on declare String variable ************'
name= listviewName.SelectedItems(0).SubItems(0).Text
room = listviewName.SelectedItems(0).SubItems(1).Text
subject = listviewName.SelectedItems(0).SubItems(2).Text
date= listviewName.SelectedItems(0).SubItems(3).Text
period= listviewName.SelectedItems(0).SubItems(4).Text
'*********** delete **************'
cmd1.Connection = MYSQLCON
MYSQLCON.Open()
cmd1.CommandText = "DELETE FROM tablename WHERE columnname = '" & name & "'"
reader = cmd1.ExecuteReader
MYSQLCON.Close()
End If

Related

Find which form field points to which database fields in MS Access

Let me explain the WEIRDEST client requirement, we're scratching our heads for:
We have an MS Access VBA application with thousands of forms fields in hundreds of forms.
A few fields in these forms populates data from few tables/queries.
A few other fields in forms inserts data to few tables through queries/direct code.
Notice that these tables are linked tables to SQL Server tables.
Is there a way to find which form field is related to which table column in?
Hence, we need some tool/macro to do this.
How do we find which form field points to which database fields in MS Access?
Based on #ClintB's answer, we have prepared the following code. The values in ctl.ControlSource doesn't seems to be referring to actual database objects:
Sub GetFormFieldToDBFieldMapping()
Dim frm As Object
Dim LiveForm As Form
Dim ctl As control
Dim i As Integer
Dim fso As Object
Dim ctlSource As String
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = fso.CreateTextFile("D:\ControlSources.txt")
For Each frm In Application.CurrentProject.AllForms
'To access form controls, open it
DoCmd.OpenForm frm.Name, acViewDesign
Set LiveForm = forms(frm.Name)
For i = 0 To LiveForm.Controls.Count - 1
Set ctl = LiveForm.Controls.Item(i)
If ctl.ControlType = 106 Or ctl.ControlType = 111 Or ctl.ControlType = 110 Or ctl.ControlType = 109 Then
ctlSource = ctlSource & vbCrLf & "Form Name :" & LiveForm.Name & ": Control Name :" & ctl.Name & ": Control Source :" & ctl.ControlSource
End If
Next i
'Do not forget to close when you are done
DoCmd.Close acForm, frm.Name
Next
oFile.WriteLine ctlSource
oFile.Close
Set fso = Nothing
Set oFile = Nothing
End Sub
I Would do something like this. (not actual code)
For each form in db
For each control in form
'Write a record to a table stating which formName, controlName and the control.controlSource
Next
Next
Edit: ControlSource, not RowSource
The code, you've came up with is excellent! This will give you:
Form Name
Control Name
Control Source
The only thing you need is the table name to which the column is coming.
Since, the tables are tables linked to SQL server, you can find all the tables with all their columns.
This will give you:
Table Name
Column Name
Keep both these information in two excel sheets.
Do a V-Lookup on column name to find the table name

How to update current row on access database table with a print button?

I have a Login form and a data entry form. When a user login, the form will pass its UserID on the next form.
After the user is done filling up the data entry form, he/she needs to print the form and the form will automatically refresh. All the data will be saved on the FormTable so as the UserID that has made the data entry.
My problem is every time I print/save all the data are saved except the UserID has a 0 value. But after the second print/save the previous row's UserID will be updated with the UserID the same is true after the next print/save. I need the UserID field to be updated in real time not 1 row behind.
Here's my code. Can you please help me fix it? Thanks!
If Not IsNull(collect) Then
'sql = "INSERT INTO cedula_tbl (Collector) VALUES ('" & collect & "')"
sql = "UPDATE cedula_tbl SET collector=('" & collect & "') WHERE cedula_no=DMax('cedula_no', 'cedula_tbl')"
db.Execute (sql)
End If

How to delete multiple rows in datagridview and database using vb.net window forms

I have a data gridview which loads with these codes:
mycom.Connection = cn
mycom.CommandText = <SQL> SELECT UserName,Activity,CDate as `Date` FROM tbl_activity </SQL>.Value
Dim myadap As New MySqlDataAdapter(mycom)
Dim mydt As New DataTable
grdActivity.Columns.Add(colCB)
myadap.Fill(mydt)
grdActivity.DataSource = mydt
myadap.Dispose()
And i have my delete button with these codes:
Dim selected As Integer
selected = grdActivity.SelectedRows.Count
If grdActivity.SelectedRows.Count > 0 Then
'you may want to add a confirmation message, and if the user confirms delete
For a As Integer = 0 To selected
myr.Close()
mycom.Connection = cn
mycom.CommandText = "Delete from tbl_activity where ID = '" & a & "' "
mycom.ExecuteReader()
myr.Close()
Next
Else
MessageBox.Show("Select 1 row before you hit Delete")
End If
Can anyone help me with the right codes so i can delete databases bounded rows not only in my datagridview but also directly from the database.. thanks..
Don't dispose of the DataAdapter, you can use it to update the database. If you configure myadap with the appropriate INSERT, UPDATE and DELETE commands your button click code becomes nothing more than error handling and:
myadapt.Update(mydt)
Don't read data out of the grid, let the grid manipulate the data it is bound to and the DataAdapter will handle the rest.
I have a complete example (for MS SQL server) here

Check if Access Database Record Exists

I am using a VB program connected to an access database. In my code, I want to check if a record exists at the specified row, and if not, do something. Checking if the row exists is my issue. In pseudocode, this is what I want to achieve:
If RecordAtLocationExists = False Then
...
End If
Code I have tried includes:
If DBDataSet.Tables(TableName).Rows(QuestionNumber).IsNull = True Then
If DBDataSet.Tables(TableName).Rows(QuestionNumber) = "" Then
If DBDataSet.Tables(TableName).Rows(QuestionNumber) = Nothing Then
If DBDataSet.Tables(TableName).Rows(QuestionNumber) = Null Then
None of the above code works. I have tried to search for a solution, but everything else seems far too complicated for this. I am probably approaching this wrong, but hopefully it makes sense what I am trying to achieve.
Any ideas?
First of all, you are trying to check if the record exists at a DataTable, not at database. Database data could have changed since you filled your DataTable. Try to query the database directly:
Dim specificRow as Integer = 23 '<-- Set this variable to the specific row you are looking for
Dim query As String = "SELECT * FROM TableName WHERE QuestionNumber = ?"
Dim cmd As OleDbCommand = New OleDbCommand(query, myConnection)
cmd.Parameters.AddWithValue("questionnumber", specificRow)
dr = cmd.ExecuteReader
And test if the command return rows
If dr.Read() Then
' Do stuff here
Else
' Do another stuff here
End if

Filter subform using combobox

This has taken me nearly 2 weeks and I don't know what else to do. I have a main form (UserSearch) that has a subform (TestUserSub). The associated table for both forms is tblusers.
very simple; on the main form (UserSearch) I have a ComboBox associated with the fields in the tblusers eg cmbid, cmbname, cmbdept and so on. All I want, is for a user to make a selection from any of these comboboxes and for the associated fields to display in the subform (TestUserSub). I have tried several different versions of code in the after update event in a couple of the ComboBoxes and nothing is happening in the subform or in other instances I get error message.
One example i have tried is filtering running an SQL command
Private Sub cmbid_AfterUpdate()
Dim strSQL As String
If IsNull(Me.cmbaccess) Then
Me.RecordSource = "tblusers"
Else
strSQL = "SELECT tblUsers.[Team Member_ID] FROM tblUsers " & _
"WHERE (((tblUsers.[Team Member_ID])= " & [form_testusersub].[txtid2]))& ";"
Me.RecordSource = strSQL
End If
End Sub
The above didn't work... Can someone please help me with this. I have a sample database that I have been working off of and by some very strange way, they have managed to do this same thing without calling any code. Is this possible?
I was able to figure out the code using the sample below
Private Sub yourcombobox_AfterUpdate()
Dim LSQL As String
If IsNull(Me.yourcombobox.Value) Then
Form_yoursubform.RecordSource = "tablename"
Me.yoursubform.Requery
requerysubform 'macro to requery the whole form
Else
LSQL = "select * from tablename"
LSQL = LSQL & " where field= '" & yourcombobox & "'"
Form_yoursubform.RecordSource = LSQL
requerysubform 'macro to requery the whole form
End If
End Sub
hope this helps.

Resources