How to Load DataGridView Fast - vb.net

How can I load my data view faster?? I only have less than 300 data but it loads at least 10 secs.
here is my code
Public Class frmPopupStockout
Private Sub tsSelect_Click(sender As Object, e As EventArgs) Handles tsSelect.Click
Try
With frmStockOut
.txtPROCODE.Text = dtgList.CurrentRow.Cells(1).Value
Me.Close()
.txtJOS.Focus()
End With
Catch ex As Exception
End Try
End Sub
Private Sub FrmPopupStockout_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
query = "SELECT PROCODE as [Part Number - Location - Process], PName AS [Part Name],PNumber AS [Part Number], STOCKLOC AS [Location],PROQTY AS [Quantity], PROCS AS [Process] FROM tblProductInfo"
retrieve(query, dtgList)
End Sub
Private Sub txtSearch_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
query = "SELECT PROCODE as [Part Number - Location - Process], PName AS [Part Name],PNumber AS [Part Number], STOCKLOC AS [Location],PROQTY AS [Quantity], PROCS AS [Process] FROM tblProductInfo WHERE PROCODE LIKE '%" & txtSearch.Text & "%'"
retrieve(query, dtgList)
End Sub
Private Sub tsClose_Click(sender As Object, e As EventArgs) Handles tsClose.Click
Me.Close()
End Sub
End Class
Here is the code on retrieve query
Public Sub retrieve(ByVal query As String, ByVal dtg As DataGridView)
Try
con.Open()
cmd = New OleDb.OleDbCommand
With cmd
.Connection = con
.CommandText = query
End With
da = New OleDb.OleDbDataAdapter
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
dtg.Columns.Clear()
dtg.Columns.Add("count", "#")
dtg.DataSource = dt
Dim MAXROW As Integer = dt.Rows.Count - 1
For i = 0 To MAXROW
dtg.Rows(i).Cells(0).Value = i
Next
With dtg
.Columns(0).Width = 18
' .Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
'.Columns(1).Visible = False
.Font = New Font("arial", 8, FontStyle.Bold)
.SelectionMode = False
End With
Catch ex As Exception
logs(ex.Message & " at retrieve sub Procedure")
MsgBox(ex.Message)
Finally
con.Close()
da.Dispose()
End Try
End Sub
When ever I try to load the Form with data grid it freezes for a while then it will load the form together with data.
I am retrieving the data from MS Access database, which have the front end together with the application and the backend at the Network Shared Files.

Problem Solved
I set these 2 from AllCells to DisplayedCells or None (AutosizeColumnsMode and AutoSizeRowsMode. and viola it loads faster
enter image description here

Related

DataGridView refreshing fixed position in row filter textbox in vb.net

I want when filtering rows in the textbox then the database is updated from other applications then I do a refresh I want the datagridview that I filter in the textbox in a fixed position and also when selected in the combobox as well. Maybe my code isn't perfect. So there may be the best solution.
Thanks
VIEW DATAGRIDVIEW
Public Class Form1
Dim Path As String = Application.StartupPath()
Dim cn = "provider=Microsoft.Jet.OLEDB.4.0; data source=" & Path & "; Extended Properties=dBase IV"
Private WithEvents dt As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.PopulateComboBox()
Me.PopulateDataGridView()
Me.clearfiltercombobox()
End Sub
Private Sub PopulateDataGridView()
Try
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0 AND BRAND = #BRAND"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#BRAND", ComboBox1.SelectedValue)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.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 TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
CType(DataGridView1.DataSource, DataTable).DefaultView.RowFilter = String.Format("ITM LIKE '%{0}%' OR ITM LIKE '%{0}%'", TextBox1.Text)
Catch ex As Exception
MsgBox("No match found")
End Try
End Sub
Private Sub ComboBox1_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectionChangeCommitted
Me.TextBox1.Text = ""
Me.PopulateDataGridView()
End Sub
Private Sub PopulateComboBox()
Dim query As String = "SELECT DISTINCT BRAND FROM EXAMPLE WHERE QTY > 0"
Try
Using con As OleDbConnection = New OleDbConnection(cn)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(query, con)
'Fill the DataTable with records from Table.
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
'Insert the Default Item to DataTable.
Dim row As DataRow = dt.NewRow()
row(0) = ""
dt.Rows.InsertAt(row, 0)
'Assign DataTable as DataSource.
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "BRAND"
ComboBox1.ValueMember = "BRAND"
End Using
End Using
Catch myerror As OleDbException
MessageBox.Show("Error: " & myerror.Message)
Finally
End Try
End Sub
Private Sub clearfiltercombobox()
Try
ComboBox1.ResetText()
TextBox1.Text = ""
Dim query = "select ITM,ART,QTY FROM EXAMPLE WHERE QTY > 0"
Using con As OleDbConnection = New OleDbConnection(cn)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
Using adapter As New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
adapter.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 Refreshonly_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Refreshonly.Click
Me.clearfiltercombobox()
DataGridView1.Refresh()
End Sub
Private Sub clearall_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Clearall.Click
Me.clearfiltercombobox()
End Sub
End Class

show patients that had a certain type of diagnose

I have a patient database. In that database i have a table "diagnosetypes" and a table with dossiers with a patient that received a certain diagnose.
In my diagnose form i have a list of diagnoses and now i want to add a listbox with a filter on all patients/dossiers that had this certain diagnose when that diagnose is selected in the combobox.
this is my current code
Public Class Diagnoses
Private Sub Diagnoses_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Tbl_DossiersTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Dossiers)
Me.Tbl_DiagnosesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Diagnoses)
Dim dt = Tbl_DiagnosesBindingSource
cboxDiagnose.DataSource = dt
cboxDiagnose.DisplayMember = "Diag_Type"
txtDiagnoseBeschrijving.Text = dt(0)("Diag_Type").ToString
cboxDiagnose.Focus()
End Sub
Private Sub CboxDiagnose_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cboxDiagnose.SelectionChangeCommitted
txtDiagnoseBeschrijving.Text = DirectCast(cboxDiagnose.SelectedItem, DataRowView)("Diag_Beschrijving").ToString
End Sub
Private Sub CboxDiagnose_Click(sender As Object, e As EventArgs) Handles cboxDiagnose.Click
RefreshData()
End Sub
Private Sub BtnAddDiagnose_Click(sender As Object, e As EventArgs) Handles btnAddDiagnose.Click
FormMakeDiagnoseType.Show()
End Sub
Private Sub RefreshData()
Try
Me.Tbl_DiagnosesBindingSource.Filter = Nothing
Me.Tbl_DiagnosesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Diagnoses)
Catch ex As Exception
MsgBox("Refresh Data Error: " & ex.Message.ToString(),
MsgBoxStyle.OkOnly Or MsgBoxStyle.Information, "Add New Record Failed!")
End Try
End Sub
End Class
edit: I changed my code to look like this as a way of trying to accomplish it myself , but i won't work.
Private Sub Diagnoses_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\GoogleDrive\EINDWERK VBNET\PatientenDatabase.accdb")
cn.Open()
Dim cmmd As New OleDb.OleDbCommand("SELECT * FROM tbl_Dossiers WHERE OZ_ID.value = cboxDiagnose.text", cn)
Dim dr As OleDb.OleDbDataReader
dr = cmmd.ExecuteReader
Do While dr.Read
lboxPat_Diagcombo.Items.Add(dr("Rel_naam"))
Loop
cn.Close()
found something that works!
defined a binding source in code
then linked the listbox datasource to the binding source
then added following code :
Private Sub Onderzoeken_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Tbl_DossiersTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_Dossiers)
Me.Tbl_OnderzoeksTypesTableAdapter.Fill(Me.PatientenDatabaseDataSetX.tbl_OnderzoeksTypes)
Dim dt = Tbl_OnderzoeksTypesBindingSource
cboxOnderzoek.DataSource = dt
cboxOnderzoek.DisplayMember = "OZ_TypeOnderzoek"
cboxOnderzoek.ValueMember = "OZ_ID"
rtbBeschrijvingOnderzoek.Text = dt(0)("OZ_TypeOnderzoek").ToString
cboxOnderzoek.Focus()
Private Sub CboxDiagnose_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles cboxOnderzoek.SelectionChangeCommitted
rtbBeschrijvingOnderzoek.Text = DirectCast(cboxOnderzoek.SelectedItem, DataRowView)("OZ_Onderzoeksbeschrijving").ToString
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\GoogleDrive\EINDWERK VBNET\PatientenDatabase.accdb")
cn.Open()
Dim ssql As String = "Select Rel_ID, tbl_Relaties.Rel_Naam &' ' & Rel_Voornaam as totaleNaam " &
"From tbl_Relaties INNER Join (tbl_Dossiers INNER Join tbl_DossRelatie On " &
"tbl_Dossiers.Dos_ID = tbl_DossRelatie.DR_DossID) ON tbl_Relaties.Rel_ID = tbl_DossRelatie.DR_RelID WHERE OZ_ID = " & cboxOnderzoek.SelectedValue
Dim cmmd As New OleDb.OleDbCommand(ssql, cn)
Dim dr As OleDb.OleDbDataReader
dr = cmmd.ExecuteReader
If dr.HasRows Then
Application.DoEvents()
bs_Relaties.DataSource = dr
lboxOZpatientcombo.DisplayMember = "totaleNaam"
lboxOZpatientcombo.ValueMember = "Rel_ID"
End If
cn.Close()
End Sub
since i added a binding source, the rest was easier to do:
Private Sub lboxOZpatientcombo_DoubleClick(sender As Object, e As EventArgs) Handles lboxOZpatientcombo.DoubleClick
Try
Dim MPF As New MainPatientform
MPF.display(Me, bs_Relaties.Current("rel_id"))
Catch ex As Exception
End Try
End Sub
thanks to all for new insights in this matter.

How to display data in DataGridView like flight information display

I have a program that displays data from MS Access in DataGridView by Timers
I put 2 dgvs in my Form and each one should display different data from different tables.
my dgv displays 14 rows (that's the full size of monitor!).
here is what i tried:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
getDATA(dgv1, dgv2, Timer1, Timer2, "tab1")
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
getDATA(dgv2, dgv1, Timer2, Timer1, "tab2")
End Sub
Private Sub getDATA(dgv As DataGridView, vdgv As DataGridView, tm1 As Timer, tm2 As Timer, tbl As String)
Try
dgv.Visible = True
vdgv.Visible = False
If conn.State = ConnectionState.Open Then conn.Close()
Dim sqlstr As String = ""
sqlstr = "Select f1,f2,f3,f4 from " + tbl
Dim ds As New DataTable
Dim da As New OleDbDataAdapter(sqlstr, conn)
ds.Reset()
da = New OleDbDataAdapter(sqlstr, conn)
da.Fill(ds)
conn.Open()
If ds.Rows.Count = 0 Then
dgv.Rows.Clear()
Else
dgv.Rows.Clear()
dgv.Rows.Add(ds.Rows.Count)
For s = 0 To ds.Rows.Count - 1
dgv.Rows(s).Cells(0).Value = ds.Rows(s).Item("f1")
dgv.Rows(s).Cells(1).Value = ds.Rows(s).Item("f2")
dgv.Rows(s).Cells(2).Value = ds.Rows(s).Item("f3")
dgv.Rows(s).Cells(3).Value = ds.Rows(s).Item("f4")
Next s
End If
dgv.ClearSelection()
conn.Close()
tm1.Stop()
tm2.Start()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
This code is work fine, but sometimes one of the tables contains more than 14 rows!
how can i display the rest of rows in specific DGV?
should i use another Timer?

VB.Net Running a task on a different thread

I'm developing a small database management tool. I'd like the application to start up and attempt to connect to the database, but the database resides on a networked drive, so it can take a long time. During this time, the application hangs.
I'm using the below code to try and run the code to connect to the database in a different thread so that the application can load, and the database can connect separately.
Public Class Incident_Form
'DELEGATE CLASSES
Delegate Sub UpdateTable()
'DELEGATE VARIABLES
Public UpdateTableVar As UpdateTable
Private Sub Incident_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
I_List.DataSource = Nothing
Display_Module.Maximise_Window()
Splash_Panel.BringToFront()
System.Windows.Forms.Application.DoEvents()
UpdateTableVar = New UpdateTable(AddressOf Me.UpdateTableHandler)
Me.Invoke(Me.UpdateTableVar)
End Sub
Public Sub UpdateTableHandler() 'Handles the background work for updating I_LIST
If (Me.InvokeRequired) Then
Me.Invoke(UpdateTableVar)
Else
Dim myCon = New OleDbConnection(My.Settings.Database_Connection_String)
myCon.Open()
Dim ds As DataSet = New DataSet
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT [IN_REF], [Incident Name], [Date Created], [Created By] " & _
"FROM [Master_Record]"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, myCon)
adapter.Fill(ds)
I_List.DataSource = ds.Tables(0)
I_List.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
I_List.Columns(0).HeaderText = "Reference"
I_List.Sort(I_List.Columns("Date Created"), System.ComponentModel.ListSortDirection.Descending)
myCon.Close()
End If
End Sub
The issue with the above is that although the application loads and displays the form correctly, the user still cannot interact with the form until the database finishes connecting. It's like it's running in another thread but its waiting for that thread to finish before it continues.
Is there something I'm missing or is this not the correct approach?
UPDATE 1
Thanks for the help, I've updated the code to the following and all is working correctly :)
Public Class Incident_Form
Dim ds As DataSet = New DataSet
Private Sub Incident_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
I_List.DataSource = Nothing
Display_Module.Maximise_Window()
Splash_Panel.BringToFront()
System.Windows.Forms.Application.DoEvents()
Try
BackgroundWorker1.RunWorkerAsync()
Catch ex As Exception
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.CancelAsync()
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
UpdateTableHandler()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
I_List.DataSource = ds.Tables(0)
I_List.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
I_List.Columns(0).HeaderText = "Reference"
I_List.Sort(I_List.Columns("Date Created"), System.ComponentModel.ListSortDirection.Descending)
End Sub
Public Sub UpdateTableHandler() 'Handles the background work for updating I_LIST
Dim myCon = New OleDbConnection(My.Settings.Database_Connection_String)
myCon.Open()
Dim adapter As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT [IN_REF], [Incident Name], [Date Created], [Created By] " & _
"FROM [Master_Record]"
adapter.SelectCommand = New OleDb.OleDbCommand(sql, myCon)
adapter.Fill(ds)
myCon.Close()
End Sub
Replace your DoEvents() call with BackgroundWorker by adding it to your form.
Private Sub Incident_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
I_List.DataSource = Nothing
Display_Module.Maximise_Window()
Splash_Panel.BringToFront()
Try
BackgroundWorker1.RunWorkerAsync()
Catch ex As Exception
BackgroundWorker1p.WorkerSupportsCancellation = True
BackgroundWorker1.CancelAsync()
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As
System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
UpdateTableHandler()
End Sub

Asset Dataset Button

I have been trying to write a program for a company that I work for, that would do assist tracking as well as give an overview of where the assists are.
The idea is to have a database with unique numbers on them that is allocated to all the hardware.
When a "desk" button is pressed it will show the info form that desk and it can be edited from there.
I roughly have what I was looking for, but I'm struggling with an issue when I update data, the data is somehow placed in the incorrect row...
E.g:
Desk Name : TL1
PC : 0001
monitor : 0002
Desk Name : TL2
PC : 0003
monitor : 0004
If I update the fist data entry alone it works fine.. however when I update the second entry it gets saved onto the first entry
E.g:
Desk Name : TL2
PC : 0003
monitor : 0004
Desk Name : TL2
PC : 0003
monitor : 0004
This is the code I have so far, any help would be very appreciated.
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim MaxRows As Integer
Dim inc As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Lib_9th_NLDataSet.tblContacts' table. You can move, or remove it, as needed.
Me.TblContactsTableAdapter.Fill(Me.Lib_9th_NLDataSet.tblContacts)
dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
dbSource = "Data Source = \\elite03\IT\Assets\Lib 9th NL.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT Desk,Pc,Monitor,Keyboard,Phone,Laptop FROM tblcontacts"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Lib_9th_NL")
con.Close()
MaxRows = Lib_9th_NLDataSet.tblContacts.Rows(inc).Item(inc)
inc = 0
End Sub
Private Sub NavigateRecords()
txtDesk_Name.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(0)
txtPC.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(1)
txtMonintor.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(2)
txtKeyboard.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(3)
txtPhone.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(4)
txtlaptop.Text = ds.Tables("Lib_9th_NL").Rows(inc).Item(5)
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Me.Validate()
Me.TblContactsBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.Lib_9th_NLDataSet)
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 0 Then
inc = inc + 1
NavigateRecords()
Else
MsgBox("No More Rows")
End If
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
NavigateRecords()
Else
MsgBox("First Record")
End If
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
btnCommit.Enabled = True
btnUpdate.Enabled = False
btnDelete.Enabled = False
btnAddNew.Enabled = False
txtDesk_Name.Clear()
txtPC.Clear()
txtMonintor.Clear()
txtKeyboard.Clear()
txtPhone.Clear()
txtlaptop.Clear()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
btnCommit.Enabled = False
btnAddNew.Enabled = True
btnUpdate.Enabled = True
btnDelete.Enabled = True
inc = 0
NavigateRecords()
End Sub
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Lib_9th_NL").NewRow()
dsNewRow.Item("desk") = txtDesk_Name.Text
dsNewRow.Item("PC") = txtPC.Text
dsNewRow.Item("Monitor") = txtMonintor.Text
dsNewRow.Item("Keyboard") = txtKeyboard.Text
dsNewRow.Item("Phone") = txtPhone.Text
dsNewRow.Item("Laptop") = txtlaptop.Text
ds.Tables("Lib_9th_NL").Rows.Add(dsNewRow)
da.Update(ds, "Lib_9th_NL")
MsgBox("New Record added to the Database")
btnCommit.Enabled = False
btnAddNew.Enabled = True
btnUpdate.Enabled = True >
btnDelete.Enabled = True
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
If MessageBox.Show("Do you really want to Delete this Record?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")
Exit Sub
End If
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("Lib_9th_NL").Rows(inc).Delete()
MaxRows = MaxRows - 1
inc = 0
da.Update(ds, "Lib_9th_NL")
NavigateRecords()
End Sub
Private Sub TL1_Click(sender As Object, e As EventArgs) Handles TL1.Click
txtDesk_Name.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(1)
txtPC.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(2)
txtMonintor.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(3)
txtKeyboard.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(4)
txtPhone.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(5)
txtlaptop.Text = Lib_9th_NLDataSet.tblContacts.Rows(0).Item(6)
End Sub
Private Sub Ret1_Click(sender As Object, e As EventArgs) Handles Ret1.Click
txtDesk_Name.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(1)
txtPC.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(2)
txtMonintor.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(3)
txtKeyboard.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(4)
txtPhone.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(5)
txtlaptop.Text = Lib_9th_NLDataSet.tblContacts.Rows(1).Item(6)
End Sub
End Class
It seems like you might be getting mixed up between your DataSet and your TableAdapterManager.
First, we need to get the values from the text boxes.
empID = EmployeeIDTxt.Text
dob = DateOfBirthTxt.Text
mailStation = MailStationTxt.Text
eFirst = FNameTxt.Text
prefName = PrefNameTxt.Text
eLast = LNameTxt.Text
homeAddress = Address1Txt.Text
city = CityTxt.Text
state = StateTxt.Text
zip = ZipTxt.Text
payGroup = PayGroupTxt.Text
fileNo = FileNoTxt.Text
begDT = BegDtTxt.Text
Now, we can reference the fields in our Update query as variables, and add parameters to them so we can prevent SQL Injection.
'This is your update statement
Dim updateQry As String = String.Empty
updateQry = "UPDATE YOURTABLE"
updateQry &= " SET EMPL_ID = #EmployeeID,EMPL_LAST_NM = #LastName, EMPL_FIRST_NM = #FirstName, EMPL_PREFRD_NM = #PrefName,"
updateQry &= " EMPL_BIRTH_DT = #DateOfBirth, EMPL_MAIL_STN_CD = #MS, EMPL_ADDR1_TXT = #HomeAddress,"
updateQry &= " EMPL_ADDR2_TXT = #Add2, EMPL_CITY_NM = #City, EMPL_STATE_CD = #State, EMPL_POSTL_CD = #Zip,"
updateQry &= " WHERE EMPL_ID = #EmployeeID ;"
'Declare Connection String
Using sqlConnection As New OleDBConnection(myConn)
Using cmd As New OleDBCommand()
'Declare variable for SQL command
With cmd
.Connection = sqlConnection
.CommandType = CommandType.Text
.CommandText = updateQry
'Prevent against SQL Injection -> Add Parameters
With .Parameters
.AddWithValue("#EmployeeID", empID)
.AddWithValue("#FirstName", eFirst)
.AddWithValue("#LastName", eLast)
.AddWithValue("#PrefName", prefName)
.AddWithValue("#DateOfBirth", dob)
.AddWithValue("#MS", mailStation)
.AddWithValue("#HomeAddress", homeAddress)
.AddWithValue("#City", city)
.AddWithValue("#State", state)
.AddWithValue("#Zip", zip)
End With
End With
Try
sqlConnection.Open()
cmd.ExecuteNonQuery()
Catch ex As Exception
MessageBox.Show("Error Updating " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Using
End Using
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
MsgBox("" & FNameTxt.Text & " " & LNameTxt.Text & " has been updated")
End Try
Now, we need to change a few things.
Replace myConn with your connection string and open it in this instance (in the btnUpdate sub)
Change all of the fields in the Parameter list to your variables. ("EmployeeID" is the parameter I am providing for the variable empID)
Your WHERE clause is going to depend on what records you want to update. That's for you to decide. Is there a primary key you can reference like I do with EmployeeID?
Replace EMPL_ fields with your field names.
For clarification, the "#EmployeeID" parameter is the safe way of writing to the database of adding empID directly.
There are a couple other ways to do this, such as OleDbUpdateCommand, etc.
Hope this helps you.